R使用ifelse更改因子值

R使用ifelse更改因子值,r,if-statement,R,If Statement,我有一列是因子变量。我需要更改所有单元格的值,其中因子是某个很少发生的级别。我正在使用以下代码,但它似乎不起作用: test2$timeFactor <- ifelse(test2$timeFactor == '94', '-1000', test2$timeFactor) test2$timeFactor这样行吗 test2 <- transform(test2, timeFactor = ifelse(timeFactor == '94', '-1000', timeFact

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

test2$timeFactor <- ifelse(test2$timeFactor == '94', '-1000', test2$timeFactor)
test2$timeFactor这样行吗

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

test2您最好更改
级别

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
set.seed(1)

以下语法提供了更大的灵活性:
levels(x)
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