2012-04-17 95 views
2

我有一列是因子变量。我需要更改所有单元格的值,其中该因素是某个很少发生的级别。我使用下面的代码,但它似乎并不奏效:R使用ifelse来更改因子值

test2$timeFactor <- ifelse(test2$timeFactor == '94', '-1000', test2$timeFactor) 

我也试过:

test2$timeFactor <- factor(ifelse(test2$timeFactor == '94', '-1000', test2$timeFactor)) 

但既不似乎工作。我在这里错过的任何明显的东西?

回答

9

你最好改变levels

set.seed(1) 
x <- factor(sample(letters[1:3],10,replace=T)) 
x 
[1] a b b c a c c b b a 
Levels: a b c 

levels(x)[which(levels(x)=="c")] <- "z" 
x 
[1] a b b z a z z b b a 
Levels: a b z 
+1

下面的语法提供了更大的灵活性:'水平(X)< - 列表(= “A”,B = “B”,Z =“c”)',但如果有很多关卡,它可能很乏味。 – 2012-04-17 16:01:40

1

这项工作?

test2 <- transform(test2, timeFactor = ifelse(timeFactor == '94', '-1000', timeFactor))