string 如何将字符列表折叠为 R 中的单个字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9314328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:23:01  来源:igfitidea点击:

How to collapse a list of characters into a single string in R

stringrstring-concatenation

提问by userJT

There is a list which I would like to output into an excel file as a single string. I start with a list of characters.

有一个列表,我想将其作为单个字符串输出到 excel 文件中。我从一个字符列表开始。

  url="http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=21558518&retmode=xml"
  xml = xmlTreeParse(url,useInternal = T)
  ns <- getNodeSet(xml, '//PublicationTypeList/PublicationType')  
  types <- sapply(ns, function(x) { xmlValue(x) } )  
  types

Output is this:

输出是这样的:

[1] "Journal Article"                      "Multicenter Study"                    "Research Support, N.I.H., Extramural"
[4] "Research Support, Non-U.S. Gov't"    

So in types - there is a list of characters Now I need to make into a single string. This is what I have so far but it is not optimal:

所以在类型中 - 有一个字符列表现在我需要变成一个字符串。这是我到目前为止所拥有的,但不是最佳的:

 types_as_string = as.character(types[[1]])
      if (length(types) > 1) for (j in 2:length(types))   types_as_string = paste(types_as_string,"| ",as.character(types[[j]]),sep="")
 types_as_string          
 [1] "Journal Article| Multicenter Study| Research Support, N.I.H., Extramural| Research Support, Non-U.S. Gov't"

So I want to end up with a nice string separated by pipes or other separator. (the last code part - is what I want to re-write nicely). The pipes are important and they have to be properly done.

所以我想得到一个由管道或其他分隔符分隔的漂亮字符串。(最后的代码部分 - 是我想很好地重写的部分)。管道很重要,必须正确完成。

回答by ilya

You can do it with pastefunction

你可以用paste函数来做

    > paste(c('A', 'B', 'C'), collapse=', ' )
    [1] "A, B, C"

回答by Chernoff

You can do it with str_cfunction

你可以用str_c函数来做

> library('stringr')
> str_c(c('A','B','C'),collapse=',')    
[1] "A,B,C"