yrx1702
yrx1702

Reputation: 1651

List of characters to character vector

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.

Upvotes: 3

Views: 987

Answers (4)

ThomasIsCoding
ThomasIsCoding

Reputation: 102730

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"

Upvotes: 1

akrun
akrun

Reputation: 887911

An option with rrapply

library(rrapply)
unname(rrapply(stringlist, f = paste, collapse="", how = 'unlist'))
#[1] "a"  "b"  "ab" "c"  "d"  "cd"

Upvotes: 2

jay.sf
jay.sf

Reputation: 73712

Using rapply.

unname(rapply(stringlist, paste, collapse=""))
# [1] "a"  "b"  "ab" "c"  "d"  "cd"

Upvotes: 4

Ronak Shah
Ronak Shah

Reputation: 389315

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"

Upvotes: 4

Related Questions