【问题标题】:How to get combinations of two factors and convert into a new factor in R如何获得两个因素的组合并转换为R中的新因素
【发布时间】:2014-06-23 09:37:52
【问题描述】:

例如,我可以这样做:

x = c(1, 2, 3, 3, 2, 1)
y = c(rep("a", 3), rep("b", 3))
z= ifelse(x==1 & y=="a", "a1", ifelse(x==1 & y=="b", "b1", ifelse(x==2 & y=="a", "a2", ifelse(x==2 & y=="b", "b2", ifelse(x==3 & y=="a", "a3", "b3")))))
z = factor(z)

但这很繁琐,有没有更好的方法?

【问题讨论】:

  • x 不是一个因素,所以你没有在上面的代码中结合两个因素。

标签: r data-manipulation


【解决方案1】:

只需使用paste0 组合向量

factor(paste0(y, x))

或者

factor(paste(y, x, sep=""))

【讨论】:

  • interaction(y, x, sep="")
【解决方案2】:

similar thread 中所述: 如果你有xy两个因子,使用

interaction(x, y)

将根据您的需要生成一个新因子。它的水平是两个因素水平的所有可能组合(对)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-21
    • 2013-02-15
    • 1970-01-01
    • 2019-01-30
    相关资源
    最近更新 更多