R使用ifelse来改变因子值

scr*_*Owl 2 if-statement r

我有一个因子变量列.我需要更改因子是某个很少发生的水平的所有细胞的值.我正在使用以下代码但它似乎没有工作:

test2$timeFactor <- ifelse(test2$timeFactor == '94', '-1000', test2$timeFactor)
Run Code Online (Sandbox Code Playgroud)

我也尝试过:

test2$timeFactor <- factor(ifelse(test2$timeFactor == '94', '-1000', test2$timeFactor))
Run Code Online (Sandbox Code Playgroud)

但似乎都不起作用.有什么明显我在这里不见了?

Jam*_*mes 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
Run Code Online (Sandbox Code Playgroud)