1

I have a nested list

l1 <- letters
l2 <- 1:26
l3 <- LETTERS
list <- list(l1,l2,l3)

Is there an elegant way to concatenate all the elements in inner vectors to form one character vector (possibly using paste), the assumption is that all the inner vectors are of the same length.

I would like my final result to be

[1] "a1A"
[2] "b2B"
[3] "c3C"
[4] "d4D"
....
[26] "z26Z"
Jaap
  • 81,064
  • 34
  • 182
  • 193

2 Answers2

1

Try:

apply(sapply(list,paste0),1,paste0,collapse="")
[1] "a1A"  "b2B"  "c3C"  "d4D"  "e5E"  "f6F"  "g7G"  "h8H"  "i9I"  "j10J" "k11K" "l12L" "m13M" "n14N" "o15O" [16] "p16P" "q17Q" "r18R" "s19S" "t20T" "u21U" "v22V" "w23W" "x24X" "y25Y" "z26Z"
Chriss Paul
  • 1,101
  • 6
  • 19
1

user20650's solution is probably as elegant as you are going to get. But for what it's worth, here's a quick hack in dplyr:

library(dplyr)

ll <- list(l1,l2,l3) # I try not to use "list" as a name. Gets confusing sometimes.

as.data.frame(ll) %>% 
  mutate(x = paste0(.[[1]], .[[2]], .[[3]])) %>% 
  .$x

# returns
 [1] "a1A"  "b2B"  "c3C"  "d4D"  "e5E"  "f6F"  "g7G"  "h8H"  "i9I"  "j10J" "k11K" "l12L"
[13] "m13M" "n14N" "o15O" "p16P" "q17Q" "r18R" "s19S" "t20T" "u21U" "v22V" "w23W" "x24X"
[25] "y25Y" "z26Z"
Z.Lin
  • 28,055
  • 6
  • 54
  • 94
  • 3
    Even easier: `purrr::pmap(ll, paste0)` ([see also here](https://stackoverflow.com/a/41489994/2204410)). – Jaap Sep 01 '18 at 12:51