How to paste ith element of vector to ith element of list of vector

Viewed 169

I have a vector of nth element and a list with the same number of elements, each is a vector. For a simple equivalent example:

v <- c("a","b")
num1 <- c(1,2,3)
num2 <- c(10,20,30)
numList <- list(num1,num2)

The output I want is:

"a1"  "a2"  "a3"  "b10" "b20" "b30"

I can do this with a for loop:

output <- vector() 
for (i in 1:length(v)) {
  output <- c(output, paste0(v[i], numList[[i]]))
}
output

[1] "a1"  "a2"  "a3"  "b10" "b20" "b30"

But is there an easier or more clever way, using lapply or tidyverse? I tried the following and did not get what I want:

lapply(numList, function(x) paste0(v, x))
2 Answers

We can try the base R code below

> c(sapply(seq_along(v), function(k) paste0(v[k], numList[[k]])))
[1] "a1"  "a2"  "a3"  "b10" "b20" "b30"

We can use Map instead of lapply

unname(unlist(Map(paste0, v, numList)))

-output

[1] "a1"  "a2"  "a3"  "b10" "b20" "b30"

Or stack a named list into a two column data.frame and apply the paste once

with(stack(setNames(numList, v)), paste0(ind, values))
[1] "a1"  "a2"  "a3"  "b10" "b20" "b30"

Or a faster version would be to replicate the 'v' based on the lengths of the list, unlist the list and paste

paste0(rep(v, lengths(numList)), unlist(numList))
[1] "a1"  "a2"  "a3"  "b10" "b20" "b30"

Or using map2 from purrr

library(stringr)
library(purrr)
map2(v, numList, str_c) %>%
    flatten_chr
[1] "a1"  "a2"  "a3"  "b10" "b20" "b30"
Related