3

I would like to convert a named list of characters like

stringlist = list("list1" = list("a","b",c("a","b")), 
                  "list2" = list("c","d",c("c","d")))

into a character vector

[1] "a"  "b"  "ab" "c"  "d"  "cd"

where the list objects of length > 1 are combined into a single element in the resulting character vector. The solution from this thread is

sapply(stringlist, paste0, collapse="")

which returns

              list1               list2 
"abc(\"a\", \"b\")" "cdc(\"c\", \"d\")"

so I was wondering whether there is an elegant and short solution to this problem.

yrx1702
  • 1,619
  • 15
  • 27

4 Answers4

4

Since you have a nested list unlist it one level and then use the solution that you have.

unname(sapply(unlist(stringlist, recursive = FALSE), paste0, collapse = ''))
#[1] "a"  "b"  "ab" "c"  "d"  "cd"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Else use argument `use.names` in `unlist` directly instead of adding `unname` function ie. `sapply(unlist(stringlist, recursive = F, use.names = F), paste0, collapse = "")` – yuskam Oct 09 '22 at 14:02
4

Using rapply.

unname(rapply(stringlist, paste, collapse=""))
# [1] "a"  "b"  "ab" "c"  "d"  "cd"
jay.sf
  • 60,139
  • 8
  • 53
  • 110
3

An option with rrapply

library(rrapply)
unname(rrapply(stringlist, f = paste, collapse="", how = 'unlist'))
#[1] "a"  "b"  "ab" "c"  "d"  "cd"
akrun
  • 874,273
  • 37
  • 540
  • 662
2

Another base R option is using nested sapply (but not as straightforward as the r(r)apply method)

> c(sapply(stringlist, function(x) sapply(x, paste0, collapse = "")))
[1] "a"  "b"  "ab" "c"  "d"  "cd"
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81