3

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?

Nonancourt
  • 559
  • 2
  • 10
  • 21

2 Answers2

6

With sapply:

y <- sapply(x, paste0, collapse = '')
# [1] "ab"   "c"    "def"  "gghh"
acylam
  • 18,231
  • 5
  • 36
  • 45
  • 2
    You probably know this already, but FYI for those interested, `paste0` and `paste` will give the same result in cases like this where there's only one argument (other than `collapse`) – IceCreamToucan Jun 29 '18 at 17:06
-1

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=""))
}
Fino
  • 1,774
  • 11
  • 21