How to generate the permutation of x values in y positions with fixed row sums in R?

R ProgrammingServer Side ProgrammingProgramming

To generate a permutation of x values in y positions, we can use expand.grid function. For example, if we want to generate three columns for the range of values 0 to 5 then it can be done in R by using the below command −

 Live Demo

x<−expand.grid(rep(list(0:5),3));x[rowSums(x)==3,]

Output

Var1 Var2 Var3
4 3 0 0
9 2 1 0
14 1 2 0
19 0 3 0
39 2 0 1
44 1 1 1
49 0 2 1
74 1 0 2
79 0 1 2
109 0 0 3

Examples

 Live Demo

x<−expand.grid(rep(list(0:2),3));x[rowSums(x)==2,]

Output

   Var1 Var2 Var3
3    2   0   0
5    1   1   0
7    0   2   0
11   1   0   1
13   0   1   1
19   0   0   2

Example

x<−expand.grid(rep(list(0:2),5));x[rowSums(x)==2,]

Output

  Var1 Var2 Var3 Var4 Var5
3  2    0     0     0   0
5  1    1     0     0   0
7  0    2     0     0   0
11 1    0     1     0   0
13 0    1     1     0   0 
19 0    0     2     0   0
29 1    0     0     1   0
31 0    1     0     1   0
37 0    0     1     1   0
55 0    0     0     2   0
83 1    0     0     0   1
85 0    1     0     0   1
91 0    0     1     0   1
109 0   0     0     1   1
163 0   0     0     0   2

Example

x<−expand.grid(rep(list(0:5),2));x[rowSums(x)==5,]

Output

  Var1 Var2
6 5    0
11 4   1
16 3   2
21 2   3
26 1   4
31 0   5

Example

x<−expand.grid(rep(list(0:5),3));x[rowSums(x)==5,]

Example

Var1 Var2 Var3
6 5 0 0
11 4 1 0
16 3 2 0
21 2 3 0
26 1 4 0
31 0 5 0
41 4 0 1
46 3 1 1
51 2 2 1
56 1 3 1
61 0 4 1
76 3 0 2
81 2 1 2
86 1 2 2
91 0 3 2
111 2 0 3
116 1 1 3
121 0 2 3
146 1 0 4
151 0 1 4
181 0 0 5

Example

x<−expand.grid(rep(list(0:3),3));x[rowSums(x)==3,]

Output

Var1 Var2 Var3
4 3 0 0
7 2 1 0
10 1 2 0
13 0 3 0
19 2 0 1
22 1 1 1
25 0 2 1
34 1 0 2
37 0 1 2
49 0 0 3

Example

x<−expand.grid(rep(list(0:3),4));x[rowSums(x)==3,]

Output

Var1 Var2 Var3 Var4
4 3 0 0 0
7 2 1 0 0
10 1 2 0 0
13 0 3 0 0
19 2 0 1 0
22 1 1 1 0
25 0 2 1 0
34 1 0 2 0
37 0 1 2 0
49 0 0 3 0
67 2 0 0 1
70 1 1 0 1
73 0 2 0 1
82 1 0 1 1
85 0 1 1 1
97 0 0 2 1
130 1 0 0 2
133 0 1 0 2
145 0 0 1 2
193 0 0 0 3

Example

x<−expand.grid(rep(list(0:3),2));x[rowSums(x)==3,]

Output

Var1 Var2
4 3 0
7 2 1
10 1 2
13 0 3

Example

x<−expand.grid(rep(list(0:1),5));x[rowSums(x)==1,]

Output

Var1 Var2 Var3 Var4 Var5
2 1 0 0 0 0
3 0 1 0 0 0
5 0 0 1 0 0
9 0 0 0 1 0
17 0 0 0 0 1
raja
Published on 07-Nov-2020 15:52:27
Advertisements