3

我有一列是因子变量。我需要更改因子是某个很少出现的水平的所有单元格的值。我正在使用以下代码,但它似乎不起作用:

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

我也试过:

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

但似乎都不起作用。我在这里遗漏了什么明显的东西吗?

4

2 回答 2

10

你最好改变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
于 2012-04-17T15:52:41.653 回答
1

这行得通吗?

test2 <- transform(test2,  timeFactor = ifelse(timeFactor == '94', '-1000', timeFactor) )
于 2012-04-17T15:48:00.470 回答