假设我有三个(行)向量:
c1*x1 + c2*x2 + c3*x3
我想要c(i)
所有可能的总和{{1}},其中{{1}}为零或一。显然有八种这样的组合。我希望在更大规模的R中做到这一点(有8个向量,所以256行矩阵),但我是一个编码业余爱好者并且正在努力。
答案 0 :(得分:3)
#these vector should be combined in one data structure when you create them
x1 = c(0, 1, 0, 1, 0)
x2 = c(1, 2, 3, 4, 5)
x3 = c(2, 3, 4, 5, 6)
#create a matrix
m <- cbind(x1, x2, x3)
#all combinations of coefficients
coef <- t(do.call(expand.grid, rep(list(c(0, 1)), 3)))
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
#Var1 0 1 0 1 0 1 0 1
#Var2 0 0 1 1 0 0 1 1
#Var3 0 0 0 0 1 1 1 1
#matrix product
m %*% coef
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
#[1,] 0 0 1 1 2 2 3 3
#[2,] 0 1 2 3 3 4 5 6
#[3,] 0 0 3 3 4 4 7 7
#[4,] 0 1 4 5 5 6 9 10
#[5,] 0 0 5 5 6 6 11 11