用一个因素替换另一个因素(在数据框内)

标签 r vector replace

我有两个因素,它们没有相同的级别数,但我想根据因素的名称和顺序,使用一个因素来替换数据框中另一个因素中的值。

我的数据如下所示,

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/

相关文章:

R在一天中的最小和最大时间获取值

r - 使用facet_wrap()在每个面板中独立放置文本后,如何更改R中的文本颜色?

C++ 将元素从一个 vector 移动到另一个 vector

c++ - 无法从 vector<T> 转换为 T

Javascript 用 8 和 9 替换字符串不起作用......但其他数字可以......?

r - dinterval() 用于区间删失数据?

r - 使用 RGLPK 在 R 中进行梦幻足球线性规划

c++ - 如何使用 128 个元素创建从 -3000 到 3000 的 vector

python - 将 pandas 数据框中的数字替换为 `nan`

php - 我需要从 SQL 字段中删除一些字符而不更改数据库