-2

I would like to generate a matrix of all combinations of 3 elements with a fixed element to get a given row sum value n. The result take this format for n=6 with fixed column V4 value equal to 1:

  V1  V2  V3  V4
   5   0   0   1
   0   5   0   1
   0   0   5   1
   4   1   0   1
   4   0   1   1
   3   2   0   1
   3   0   2   1
   2   3   1   1
   2   1   3   1
   1   2   2   1
   .   .   .   1
   .   .   .   1
   .   .   .   .
   .   .   .   .

Many thanks in advance!

sdhaoui
  • 369
  • 1
  • 10
  • Check [this](http://stackoverflow.com/questions/30858688/find-all-combinations-of-numbers-that-sum-to-a-target) and [this](http://stackoverflow.com/questions/32617501/all-possible-combinations-of-a-set-that-sum-to-a-target-value) . Maybe helpful. – Ronak Shah Dec 02 '16 at 15:22

1 Answers1

1

With expand.grid

 N = 6
 combVec=expand.grid(0:N,0:N,0:N,rep(1,(N+1)))

 subVec = combVec[rowSums(combVec)==N,]
 rownames(subVec) = NULL

 head(subVec)

 #  Var1 Var2 Var3 Var4
 #1    5    0    0    1
 #2    4    1    0    1
 #3    3    2    0    1
 #4    2    3    0    1
 #5    1    4    0    1
 #6    0    5    0    1
Silence Dogood
  • 3,587
  • 1
  • 13
  • 17