Home > Software engineering >  Is there a best way to append a list values to a sublist of a list in R?
Is there a best way to append a list values to a sublist of a list in R?

Time:05-25

Say I have a list l containing sublists, and I would like to add an element of a list at the end of each sublist of that list.

> l <- list(c(1,2,3), c(2,1,4), c(4,7,6))
> l
[[1]]
[1] 1 2 3

[[2]]
[1] 2 1 4

[[3]]
[1] 4 7 6

> a <- list(3,5,7)
> a
[[1]]
[1] 3

[[2]]
[1] 5

[[3]]
[1] 7

What I would like is:

> l
[[1]]
[1] 1 2 3 3

[[2]]
[1] 2 1 4 5

[[3]]
[1] 4 7 6 7

I've tried several options, this one gets close, but it still doesn't compute the way I want to, as it adds the whole list at the end of the list.

l <- lapply(l, c, a)

CodePudding user response:

Yes

mapply("c",l,a,SIMPLIFY=FALSE)
[[1]]
[1] 1 2 3 3

[[2]]
[1] 2 1 4 5

[[3]]
[1] 4 7 6 7

CodePudding user response:

A purrr way:

l <- list(c(1,2,3), c(2,1,4), c(4,7,6))
a <- list(3,5,7)

purrr::map2(l,a, append)

Output:

[[1]]
[1] 1 2 3 3

[[2]]
[1] 2 1 4 5

[[3]]
[1] 4 7 6 7
  • Related