2017-06-19 64 views

回答

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 
+0

最终可以使用'crossprod()' – jogo

+0

@jogo或'tcrossprod'。然而,这些需要矩阵输入,我使用't'将'expand.grid'返回的数据帧强制转换为矩阵。无论如何,OP的数据相当小,所以优化效率并不是太大的问题。 – Roland

相关问题