简体   繁体   English

R:如何在向量列表中串联字符串的向量

[英]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 : 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=""))
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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