2

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)

2 Answers2

6

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
Sotos
  • 51,121
  • 6
  • 32
  • 66
user2974951
  • 9,535
  • 1
  • 17
  • 24
2

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
Julian
  • 6,586
  • 2
  • 9
  • 33