我有两个因素,它们没有相同的级别数,但我想根据因素的名称和顺序,使用一个因素来替换数据框中另一个因素中的值。
我的数据如下所示,
x <- factor(c("one", "two", "three", "two", "three"))
y <- factor(c(NA, "foo", NA, "bar", NA))
(df <- data.frame(x, y))
x y
1 one <NA>
2 two foo
3 three <NA>
4 two bar
5 three <NA>
这就是我想要结束的地方,
x y z
1 one <NA> one
2 two foo foo
3 three <NA> three
4 two bar bar
5 three <NA> three
我应该将因子转换为字符向量吗?
最佳答案
你可以使用levels(z) <- c(levels(y), levels(x))
以便 z 具有所需的级别,但是底层整数值可能无法正确关联。您最好使用 as.character
分配给 z然后转换为因子。
例如
df$z <- as.factor( ifelse(is.na(df$y), as.character(df$x), as.character(df$y)) )
关于用一个因素替换另一个因素(在数据框内),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13593703/