2017-06-19 58 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

相關問題