【问题标题】:replace in one factor by another factor (inside dataframe)用另一个因素替换一个因素(在数据框内)
【发布时间】:2012-11-15 15:11:33
【问题描述】:

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

我的数据是这样的,

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

我应该将因子转换为字符向量吗?

【问题讨论】:

    标签: r vector replace


    【解决方案1】:

    您可以使用levels(z) &lt;- 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)) )
    

    【讨论】:

    • 亲爱的 Ricardo Saporta,感谢您抽出宝贵时间回复。我不确定如何实施您的解决方案以达到预期的结果。你能扩展你的例子吗?谢谢,埃里克
    • 感谢您扩展您的答案,底线解决了我的问题。谢谢。
    • 埃里克,没问题。很高兴它有帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-21
    • 2019-09-06
    • 1970-01-01
    • 1970-01-01
    • 2020-09-29
    • 1970-01-01
    • 2021-02-18
    相关资源
    最近更新 更多