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

风流意气都作罢 提交于 2019-12-17 16:42:03

问题


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.

  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.


回答1:


You can do it with paste function

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



回答2:


You can do it with str_c function

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


来源:https://stackoverflow.com/questions/9314328/how-to-collapse-a-list-of-characters-into-a-single-string-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!