Home > Net >  Create a list such that each element contains 2 arrays from 2 other lists in R
Create a list such that each element contains 2 arrays from 2 other lists in R

Time:12-06

I have 2 lists l1 and l2

l1=list(c("bike1","bike2","bike3"),c("bike4","bike5"))
l2=list(c("car1,car2"),c("car3","car4","car5")) 

I want to create a third list l3 such that each element of l3 should contain both the elements of l1 and l2 but as differnt arrays

the output should look something like this

l3=list(list(c("bike1","bike2","bike3"),c("car1,car2")),list(c("bike4","bike5"),c("car3","car4","car5")))

> l3
[[1]]
[[1]][[1]]
[1] "bike1" "bike2" "bike3"

[[1]][[2]]
[1] "car1,car2"


[[2]]
[[2]][[1]]
[1] "bike4" "bike5"

[[2]][[2]]
[1] "car3" "car4" "car5"

The actual list l1 and l2 contain 20 elements each

CodePudding user response:

Using Map you could do:

l3 <- Map(function(x, y) list(x, y), l1, l2)
l3
#> [[1]]
#> [[1]][[1]]
#> [1] "bike1" "bike2" "bike3"
#> 
#> [[1]][[2]]
#> [1] "car1,car2"
#> 
#> 
#> [[2]]
#> [[2]][[1]]
#> [1] "bike4" "bike5"
#> 
#> [[2]][[2]]
#> [1] "car3" "car4" "car5"
  •  Tags:  
  • r
  • Related