使用ifelse改变因子变量的值的R语言技巧

3

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

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

我也尝试过以下方法:

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

但似乎都不起作用。这里有什么明显的问题吗?
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

1
以下语法提供了更多的灵活性:levels(x) <- list(a="a", b="b", z="c"),但如果有很多级别,这可能会很繁琐。 - Joshua Ulrich

1

这个可行吗?

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接