简体   繁体   中英

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.

Using rapply .

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

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"

An option with rrapply

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

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM