【问题标题】:Matrix of combinations of two vectors [duplicate]两个向量组合的矩阵[重复]
【发布时间】:2019-07-08 17:18:10
【问题描述】:

我有两个向量,比如说:

x <- c("b", "p", "t")
y <- c("a", "e", "i")

我想得到它们可能组合的矩阵。

df <- cbind(b=c("ba", "be", "bi"), p=c("pa", "pe", "pi"), t=c("ta", "te", "ti"))
rownames(df) <- c("a", "e", "i")

我见过Possible combinations of a matrix in R,但在这里不起作用。

我也试过CJ(x,y)data.table, 但我仍然需要进一步的步骤来操纵 数据。

有没有更简单的解决方案?

【问题讨论】:

    标签: r combinations


    【解决方案1】:

    我们可以使用outer

    out <- outer(x, y, FUN = paste0)
    dimnames(out) <- list(x, y)
    

    【讨论】:

    • 完美运行...为什么我不知道该功能?
    【解决方案2】:

    我们也可以使用expand.grid

    matrix(Reduce(paste0, expand.grid(x, y)), 3)
    #      [,1] [,2] [,3]
    # [1,] "ba" "be" "bi"
    # [2,] "pa" "pe" "pi"
    # [3,] "ta" "te" "ti"
    

    【讨论】:

    • 谢谢,是的,我用过 expand.grid,但我不得不说 outer() 不那么麻烦
    • @IskandarThePupsi 是的,outer 很棒,没有一种方法可以做到。
    猜你喜欢
    • 1970-01-01
    • 2011-06-02
    • 2011-06-20
    • 2018-09-20
    • 2019-09-22
    • 1970-01-01
    • 2016-05-16
    • 2017-10-25
    • 1970-01-01
    相关资源
    最近更新 更多