2

I'm trying to produce a list by combining two vectors of the same length element-wise. Here's a reproducible example.

a <- c(1:3)
b <- c("a", "b", "c")

Using these two vectors, I hope to create the following:

goal <- list(list(1, "a"), list(2, "b"), list(3, "c"))

I've tried a few different ways, but nothing seems to work.

list(as.list(a), as.list(b)) # Not working
as.list(as.list(a), as.list(b)) # Not working as well
as.list(outer(a,b, paste)) # Not working
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
qnp1521
  • 806
  • 6
  • 20

1 Answers1

1

You use Map -

Map(list, a, b)

#[[1]]
#[[1]][[1]]
#[1] 1

#[[1]][[2]]
#[1] "a"


#[[2]]
#[[2]][[1]]
#[1] 2

#[[2]][[2]]
#[1] "b"


#[[3]]
#[[3]][[1]]
#[1] 3

#[[3]][[2]]
#[1] "c"

Or map2 in purrr -

purrr::map2(a, b, list)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213