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


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?




2 Answers
2



With sapply:


sapply


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





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)
– Ryan
Jun 29 at 17:06



paste0


paste


collapse



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=""))
}






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Opening a url is failing in Swift

Export result set on Dbeaver to CSV