简体   繁体   中英

R: How to concatenate vectors of strings in a list of vectors

I have a list of vectors of strings like this:

x=list(c("a","b"),"c",c("d","e","f"),c("gg","hh") )

I'd like to concatenate the vectors into single strings like this

y=c("ab","c","def","gghh")

I searched around but I couldn't find a similar example. Is there a smart way to do this without looping over the list elements?

With sapply :

y <- sapply(x, paste0, collapse = '')
# [1] "ab"   "c"    "def"  "gghh"

It's not the most elegant solution but this works:

x=list(c("a","b"),"c",c("d","e","f"),c("gg","hh") )

y=NULL
for(i in 1:length(x)){
  y=c(y,paste0(x[[i]],collapse=""))
}

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