How to combine list elements of different sizes in R?


To combine list elements of different sizes in R, we can use expand.grid function. For Example, if we have a list called LIST that contains elements of different sizes then we can combine those items by using the command given below −

expand.grid(LIST)

Example 1

To combine list elements of different sizes in R, use the following snippet −

List1<-list(x1=rpois(2,2),x2=rpois(2,10),x3=rpois(1,2),x4=rpois(3,5),x5=rpois(2,5))
List1

The respective Outputs as per the sizes will be as follows −

$x1
[1] 2 3
$x2
[1] 6 7
$x3
[1] 2
$x4
[1] 2 4 4
$x5
[1] 3 5

Now, to combine elements of List1 add the following code to the above snippet −

List1<-list(x1=rpois(2,2),x2=rpois(2,10),x3=rpois(1,2),x4=rpois(3,5),x5=rpois(2,5))
expand.grid(List1)

Output

If you execute all the above given snippets as a single program, it generates the following Output −

 x1  x2 x3 x4 x5
 1 2 6  2  2  3
 2 3 6  2  2  3
 3 2 7  2  2  3
 4 3 7  2  2  3
 5 2 6  2  4  3
 6 3 6  2  4  3
 7 2 7  2  4  3
 8 3 7  2  4  3
 9 2 6  2  4  3
10 3 6  2  4  3
11 2 7  2  4  3
12 3 7  2  4  3
13 2 6  2  2  5
14 3 6  2  2  5
15 2 7  2  2  5
16 3 7  2  2  5
17 2 6  2  4  5
18 3 6  2  4  5
19 2 7  2  4  5
20 3 7  2  4  5
21 2 6  2  4  5
22 3 6  2  4  5
23 2 7  2  4  5
24 3 7  2  4  5

Example 2

To combine list elements of different sizes in R, use the following snippet −

List2<-list(y1=0:2,y2=c(1,2),y3=c(2,3,4,5))
List2

The respective

Output

s as per the sizes will be as follows −

$y1
[1] 0 1 2
$y2
[1] 1 2
$y3
[1] 2 3 4 5

To combine elements of List2 add the following code to the above snippet −

List2<-list(y1=0:2,y2=c(1,2),y3=c(2,3,4,5))
expand.grid(List2)

Output

If you execute all the above given snippets as a single program, it generates the following Output −

  y1 y2 y3
 1 0 1 2
 2 1 1 2
 3 2 1 2
 4 0 2 2
 5 1 2 2
 6 2 2 2
 7 0 1 3
 8 1 1 3
 9 2 1 3
10 0 2 3
11 1 2 3
12 2 2 3
13 0 1 4
14 1 1 4
15 2 1 4
16 0 2 4
17 1 2 4
18 2 2 4
19 0 1 5
20 1 1 5
21 2 1 5
22 0 2 5
23 1 2 5
24 2 2 5

Updated on: 05-Nov-2021

401 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements