将因子数字变量转换为R中的因子字符串

时间:2016-01-03 10:27:12

标签: r

我有一个数字向量:

1 3 2 4 3 3 ...

我想将其转换为因子向量,1 = "Good"2="OK""3= "Bad"等。

1 个答案:

答案 0 :(得分:4)

我们可以factor使用levelslabels指定。

set.seed(24)
factor(sample(1:3, 10, replace=TRUE), levels=1:3, 
                       labels= c('Good', 'OK', 'Bad'))

或@David Arenburg提出的变体

factor(c('Good', 'OK', 'Bad')[sample(1:3, 10, replace=TRUE)])