如何更改一组因子的级别名称?

时间:2017-06-01 04:54:23

标签: r rstudio vectorization

如何更改一组因子的级别名称?
请检查F1的{​​{1}},Example df是6级(0~5)的因子。

如何将F1更改为3个等级(1,2,3)?

例如:if F1,新级别名称为1,如果F1 == 0 or 1,则新级别名称为2,如果为F1 == 2 or 3,则新级别名称为3. Like {{ 1}}。

F1 == 4 or 5

示例df

Expected Outcome

预期结果

library(plyr)
revalue(df$F1, c("0"="1", "1"="1","2"="2", "3"="2","4"="3", "5"="3"))
# I could do this but if there are tens or hundreds of levels, 
# I will need to do this one by one, there must be a more convenient way.  

1 个答案:

答案 0 :(得分:2)

我们可以使用data.table方法,因为对象是data.table

library(data.table)
df[, F1 := factor((F1 %/% 2)+1)]