How to convert a list of lists into a single list in R?

R ProgrammingServer Side ProgrammingProgramming

A list can contain multiple lists of different type as well as similar type elements such as data frames, vectors, matrices etcetera but accessing those elements become a little difficult task. Therefore, it is better to convert a list that contain multiple lists into a single list and it can be done using unlist function.

Example

Consider the below vectors −

set.seed(871)
x1<−sample(0:5,50,replace=TRUE)
x2<−sample(0:9,50,replace=TRUE)
x3<−sample(0:10,50,replace=TRUE)
x4<−rpois(50,10)
x5<−rpois(50,5)
x6<−round(runif(50,2,5))

Storing the above vectors into a list object by creating smaller lists of combining some vectors −

Example

List<−list(list(x1),list(x1,x2),list(x1,x6),list(x1,x2,x3),
list(x2,x4,x6),list(x3,x6),list(x2,x4),list(x3,x5),list(x1,x5),list(x1,x4,x6),
list(x1,x2,x6))
List

Output

[[1]] [[1]][[1]] [1] 2 4 5 0 3 4 0 3 5 5 5 3 1 4 2 2 1 3 0 5 4 1 1 4 1 2 5 0 0 0 5 1 2 0 1 0 4 1 [39] 1 1 4 4 5 3 1 3 3 5 4 0
[[2]] [[2]][[1]] [1] 2 4 5 0 3 4 0 3 5 5 5 3 1 4 2 2 1 3 0 5 4 1 1 4 1 2 5 0 0 0 5 1 2 0 1 0 4 1 [39] 1 1 4 4 5 3 1 3 3 5 4 0
[[2]][[2]] [1] 3 3 8 6 6 0 9 1 8 4 4 8 4 8 9 0 7 8 0 5 7 6 7 3 6 8 8 9 9 2 2 2 4 0 6 8 5 4 [39] 0 3 4 3 7 1 2 0 6 0 0 1
[[3]] [[3]][[1]] [1] 2 4 5 0 3 4 0 3 5 5 5 3 1 4 2 2 1 3 0 5 4 1 1 4 1 2 5 0 0 0 5 1 2 0 1 0 4 1 [39] 1 1 4 4 5 3 1 3 3 5 4 0
[[3]][[2]] [1] 3 2 4 3 3 4 3 5 5 4 4 5 4 5 4 5 5 4 4 5 5 5 4 2 4 2 3 3 5 2 5 4 4 3 3 3 3 4 [39] 3 3 5 5 4 4 3 4 2 5 3 3
[[4]] [[4]][[1]] [1] 2 4 5 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2 1 3 0 5 4 1 1 4 1 2 5 0 0 0 5 1 2 0 1 0 4 1 [39] 1 1 4 4 5 3 1 3 3 5 4 0
[[11]][[2]] [1] 3 3 8 6 6 0 9 1 8 4 4 8 4 8 9 0 7 8 0 5 7 6 7 3 6 8 8 9 9 2 2 2 4 0 6 8 5 4 [39] 0 3 4 3 7 1 2 0 6 0 0 1
[[11]][[3]] [1] 3 2 4 3 3 4 3 5 5 4 4 5 4 5 4 5 5 4 4 5 5 5 4 2 4 2 3 3 5 2 5 4 4 3 3 3 3 4 [39] 3 3 5 5 4 4 3 4 2 5 3 3

Converting list defined as List containing different lists into a single list −

unlist(List,recursive=F)

Output

[[1]] [1] 2 4 5 0 3 4 0 3 5 5 5 3 1 4 2 2 1 3 0 5 4 1 1 4 1 2 5 0 0 0 5 1 2 0 1 0 4 1 [39] 1 1 4 4 5 3 1 3 3 5 4 0
[[2]] [1] 2 4 5 0 3 4 0 3 5 5 5 3 1 4 2 2 1 3 0 5 4 1 1 4 1 2 5 0 0 0 5 1 2 0 1 0 4 1 [39] 1 1 4 4 5 3 1 3 3 5 4 0
[[3]] [1] 3 3 8 6 6 0 9 1 8 4 4 8 4 8 9 0 7 8 0 5 7 6 7 3 6 8 8 9 9 2 2 2 4 0 6 8 5 4 [39] 0 3 4 3 7 1 2 0 6 0 0 1
[[4]] [1] 2 4 5 0 3 4 0 3 5 5 5 3 1 4 2 2 1 3 0 5 4 1 1 4 1 2 5 0 0 0 5 1 2 0 1 0 4 1 [39] 1 1 4 4 5 3 1 3 3 5 4 0
[[5]] [1] 3 2 4 3 3 4 3 5 5 4 4 5 4 5 4 5 5 4 4 5 5 5 4 2 4 2 3 3 5 2 5 4 4 3 3 3 3 4 [39] 3 3 5 5 4 4 3 4 2 5 3 3
[[6]] [1] 2 4 5 0 3 4 0 3 5 5 5 3 1 4 2 2 1 3 0 5 4 1 1 4 1 2 5 0 0 0 5 1 2 0 1 0 4 1 [39] 1 1 4 4 5 3 1 3 3 5 4 0
[[7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