2016-12-29 42 views
1

这是我的例子:[R变化因子值

phone_make_factor <- c('apple', 'samsung', 'lg') 
phone_make_string <- c('apple','samsung','lg') 
df <- data.frame(phone_make_factor, phone_make_string) 

df$phone_make_string <-as.character(df$phone_make_string) 

df[df$phone_make_string != 'apple' & df$phone_make_string != 'samsung', 'phone_make_string'] <- 'other' 

levels(df$phone_make_factor) <- c(levels(df$phone_make_factor), 'other') 
df[df$phone_make_factor != 'apple' & df$phone_make_factor != 'samsung', 'phone_make_factor'] <- 'other' 

的代码的最后一行生成错误消息:

Error in `[<-.data.frame`(`*tmp*`, df$phone_make_factor != "apple" & df$phone_make_factor != : 
    missing values are not allowed in subscripted assignments of data frames 

什么是改变因子值的最简单的方法?我正在考虑将因子转换为字符串,然后更改值并在之后转换为因子。

有什么建议吗?

回答

0

您可以使用plyr包的revalue方法。这里有一个例子:

library(plyr) 
revalue(x, c("beta"="two", "gamma"="three")) 

在你的情况,你可以这样做:

revalue(df[df$phone_make_factor != 'apple' & df$phone_make_factor != 'samsung', 'phone_make_factor'], 'other') 

如果不工作,这可能是多一点可读性:

revalue(df$col[!df$col %in% c("apple","samsung","phone_make_factor")],"other") 

我没有测试这个。

Source