Merge two lists into one component by component

Viewed 42

I have two lists, plus an empty list:

    A <- list(1:4,5:8,9:12)
    B <- c("a","b")
    C <- vector(mode = "list")

I would like to merge A and B into C as following:

    C[[1]][1] = A[[1]]         C[[1]][2] = B
    C[[2]][1] = A[[2]]         C[[2]][2] = B
    C[[3]][1] = A[[3]]         C[[3]][2] = B

Thank you.

1 Answers

How about C <- lapply(A, function(x) list(x, B))?

for example:

A <- list(1:4,5:8,9:12)
B <- c("a","b")

C <- lapply(A, function(x) list(x, B))
# C <- lapply(A, list, B) # also works

all(
  C[[1]][[1]] == A[[1]],
  C[[2]][[1]] == A[[2]],
  C[[3]][[1]] == A[[3]],
  
  C[[1]][[2]] == B,
  C[[2]][[2]] == B,
  C[[3]][[2]] == B
)

note that you'll need double [[ since each element of C is also a list (C[[1]][[1]] rather than C[[1]][1]).

Related