如何将字符列表折叠为 R 中的单个字符串 [英] How to collapse a list of characters into a single string in R

查看:27
本文介绍了如何将字符列表折叠为 R 中的单个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个列表,我想将其作为单个字符串输出到 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')类型 <- sapply(ns, function(x) { xmlValue(x) } )类型

输出是这样的:

[1] 期刊文章" 多中心研究" 研究支持,N.I.H.,校外"[4] 研究支持,非美国政府"

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

 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]期刊文章|多中心研究|研究支持,N.I.H.,校外|研究支持,非美国政府"

<块引用>

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

解决方案

你可以用paste功能

 >粘贴(c('A','B','C'),折叠=',')[1]A、B、C"

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.

解决方案

You can do it with paste function

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

这篇关于如何将字符列表折叠为 R 中的单个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆