我在R中有一个字符向量,我想为每个向量元素分配一个特定的等级,并在我的计算中使用这个等级,我该怎么做?
例如,Degree矢量定义如下:
Degree = c("low","med","high")
我希望为每个学位分配从1到3的等级,并用他们的等级替换定义的向量的度数:
Blood_pressure = c("low","low","high","med","high")
Blood_pressure = c(1,1,3,2,3)
答案 0 :(得分:1)
只需使用as.numeric
和factor
,就像这样:
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
另一个产生命名向量的选项是创建一个命名版本的" Degree"并进行基本匹配。例如:
setNames(seq_along(Degree), Degree)[Blood_pressure]
# low low high med high
# 1 1 3 2 3