如何枚举R中矩阵中的所有组合?

时间:2018-08-16 01:40:29

标签: r matrix combinations

我正在尝试构建一个包含所有可能组合的矩阵。例如,

a=(1:2)^3 #=c(1,8)
b=(1:3)^2 #=c(1,4,9)

我想定义c这样的c=c(1+1,1+4,1+9,8+1,8+4,8+9)。我从上一个问题中学到了如何从函数c获得这样一个outer的知识。我当前的问题是,如何获得如下的矩阵M

enter image description here

谢谢!

3 个答案:

答案 0 :(得分:5)

我们可以将expand.gridouter一起使用

data.frame(expand.grid(a, b), c = c(outer(a, b, "+")))

#  Var1 Var2  c
#1    1    1  2
#2    8    1  9
#3    1    4  5
#4    8    4 12
#5    1    9 10
#6    8    9 17

其中

outer(a, b, "+") #gives

#     [,1] [,2] [,3]
#[1,]    2    5   10
#[2,]    9   12   17

答案 1 :(得分:5)

好的,这里是:

z <- outer(b, a, "+")
cbind(a[col(z)], b[row(z)], c(z))
#     [,1] [,2] [,3]
#[1,]    1    1    2
#[2,]    1    4    5
#[3,]    1    9   10
#[4,]    8    1    9
#[5,]    8    4   12
#[6,]    8    9   17

稍作调整的expand.grid解决方案。

ref <- expand.grid(b = b, a = a)
val <- do.call("+", ref)  ## or `rowSums(ref)` with an implicit `as.matrix`
cbind(ref, c = val)
#  b a  c
#1 1 1  2
#2 4 1  5
#3 9 1 10
#4 1 8  9
#5 4 8 12
#6 9 8 17

在这种情况下,结果是数据帧而不是矩阵。

答案 2 :(得分:2)

或者另一个选择是CJ

library(data.table)
CJ(a, b)[, C := V1 + V2][]
#.  V1 V2  C
#1:  1  1  2
#2:  1  4  5
#3:  1  9 10
#4:  8  1  9
#5:  8  4 12
#6:  8  9 17