简体   繁体   English

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

[英]Convert factor numeric variable to factor string in R

I have a vector of numeric: 我有一个数字向量:

1 3 2 4 3 3 ...

I want to convert it to a vector of factor, with 1 = "Good" , 2="OK" , "3= "Bad" etc. 我想将其转换为因子向量,其中1 = "Good"2="OK""3= "Bad"等。

We can use factor with levels and labels specified. 我们可以将factor与指定的levelslabels使用。

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

Or a variant suggested by @David Arenburg 或@David Arenburg建议的变体

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM