I have a character vector in R, and I want to assign a specific rank to each vector element and use this rank in my computations, how can I do this?
For example, the Degree vector is defined as follows:
Degree = c("low","med","high")
and I want to assign rank from 1 to 3 to each degree and replacing the degrees of defined vector with their ranks:
Blood_pressure = c("low","low","high","med","high")
Blood_pressure = c(1,1,3,2,3)
Simply use as.numeric
and factor
, like this:
Degree = c("low","med","high")
Blood_pressure = c("low","low","high","med","high")
as.numeric(factor(Blood_pressure, Degree))
# [1] 1 1 3 2 3
Another option, which results in a named vector, is to create a named version of "Degree" and do basic matching. For example:
setNames(seq_along(Degree), Degree)[Blood_pressure]
# low low high med high
# 1 1 3 2 3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.