How to make all the elements in a list of equal size in R?

R ProgrammingServer Side ProgrammingProgramming

We know that a list can multiple elements of different types as well as of different size. For example, a list that contains two elements then one element may contain fifteen elements and the other might have twenty-five elements. In this situation, we might want to fill the first element with ten more elements so that the size of both the elements become equal. This can be done by using lapply function as shown in the below examples.

Consider the below list −

Example

 Live Demo

set.seed(101)
x1<-rnorm(10)
x2<-rpois(20,5)
x3<-rexp(15,1.5)
x4<-sample(1:10,30,replace=TRUE)
x5<-sample(0:1,30,replace=TRUE)
x6<-rpois(25,8)
x7<-rnorm(20,4,2)
List<-list(x1,x2,x3,x4,x5,x6,x7)
List

Output

[[1]]
[1] -0.3260365 0.5524619 -0.6749438 0.2143595 0.3107692 1.1739663
[7] 0.6187899 -0.1127343 0.9170283 -0.2232594
[[2]]
[1] 6 9 3 6 8 7 2 4 4 6 4 4 3 3 5 8 3 7 1 8
[[3]]
[1] 0.6663708 0.6833283 0.8470505 0.9572860 0.3622581 1.4228982 0.2396990
[8] 0.3124750 0.7762488 0.0249382 0.2544077 0.1177009 0.4194529 0.4133933
[15] 0.1465812
[[4]]
[1] 10 9 8 1 4 9 10 3 10 6 9 9 3 1 3 7 10 7 8 8 10 1 10 4 5
[26] 2 1 7 10 8
[[5]]
[1] 0 0 1 0 0 0 0 0 0 0 1 1 0 0 0 1 1 0 0 1 1 1 1 1 1 0 1 0 0 0
[[6]]
[1] 8 6 10 8 8 9 4 9 7 6 6 8 8 8 12 8 9 12 6 13 6 11 5 8 9
[[7]]
[1] 0.3621310 1.9251108 4.6049845 1.4441077 4.2766781 3.8980318 7.7042951
[8] 6.2233505 2.9772494 2.9122378 0.5421454 4.9414991 4.0107742 6.6960916
[15] 5.4481934 7.1050983 6.6509397 3.9314698 3.2779732 2.5596692

Making all the list elements to have equal size by introducing NA’s −

Example

lapply(List,'length <-',30)

Output

[[1]] [1] -0.3260365 0.5524619 -0.6749438 0.2143595 0.3107692 1.1739663
[7] 0.6187899 -0.1127343 0.9170283 -0.2232594 NA NA
[13] NA NA NA NA NA NA [19] NA NA NA NA NA NA
[25] NA NA NA NA NA NA
[[2]] [1] 6 9 3 6 8 7 2 4 4 6 4 4 3 3 5 8 3 7 1 8 NA NA NA NA NA
[26] NA NA NA NA NA
[[3]] [1] 0.6663708 0.6833283 0.8470505 0.9572860 0.3622581 1.4228982 0.2396990
[8] 0.3124750 0.7762488 0.0249382 0.2544077 0.1177009 0.4194529 0.4133933
[15] 0.1465812 NA NA NA NA NA NA [22] NA NA NA NA NA NA NA
[29] NA NA
[[4]] [1] 1 3 10 9 3 10 4 2 1 6 9 2 2 1 6 6 2 9 10 5 2 9 2 5 3
[26] 9 10 7 4 1
[[5]] [1] 0 1 1 1 1 1 1 1 0 1 1 1 1 0 0 0 0 1 0 0 1 0 0 1 1 1 0 1 0 1
[[6]] [1] 6 11 5 8 9 3 7 5 8 9 13 5 6 8 10 8 11 14 9 11 8 6 18 6 12
[26] NA NA NA NA NA
[[7]] [1] 0.5421454 4.9414991 4.0107742 6.6960916 5.4481934 7.1050983 6.6509397
[8] 3.9314698 3.2779732 2.5596692 4.5640299 2.4189487 3.1101909 6.7299863
[15] 4.9949087 2.3712070 4.5361317 2.8155834 8.2669727 6.3454973 NA
[22] NA NA NA NA NA NA NA [29] NA NA

The last argument 30 in the apply function can be replaced by max(lengths(“List_name”)) if we don’t know the largest element.

raja
Published on 19-Oct-2020 17:55:07
Advertisements