use*_*rJT 38 string r string-concatenation
有一个列表我想作为单个字符串输出到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
Run Code Online (Sandbox Code Playgroud)
输出是这样的:
[1] "Journal Article" "Multicenter Study" "Research Support, N.I.H., Extramural"
[4] "Research Support, Non-U.S. Gov't"
Run Code Online (Sandbox Code Playgroud)
所以在类型中 - 有一个字符列表现在我需要制作一个字符串.这是我到目前为止,但它不是最佳的:
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"
Run Code Online (Sandbox Code Playgroud)
所以我想最终得到一个由管道或其他分隔符分隔的漂亮字符串.(最后一个代码部分 - 我想要很好地重写).管道很重要,必须妥善完成.
ily*_*lya 55
你可以用paste功能来做
> paste(c('A', 'B', 'C'), collapse=', ' )
[1] "A, B, C"
Run Code Online (Sandbox Code Playgroud)
最短的方法是使用基本的 toString 函数。在任何情况下,输出字符串都将包含逗号
vector<-c('A', 'B', 'C')
toString(vector)
Run Code Online (Sandbox Code Playgroud)
如果你不需要逗号
gsub(",","",toString(vector))
Run Code Online (Sandbox Code Playgroud)
如果您想要任何其他分隔符,您可以在 gsub 中替换您喜欢的任何内容,而不是用任何内容替换逗号
你可以用str_c功能来做
> library('stringr')
> str_c(c('A','B','C'),collapse=',')
[1] "A,B,C"
Run Code Online (Sandbox Code Playgroud)
也来自stringr该str_flatten函数:
library(stringr)
str_flatten(c("A", "B", "C"), ",")
[1] "A,B,C"
Run Code Online (Sandbox Code Playgroud)
stringr1.5.0 添加str_flatten_comma
str_flatten_comma(c("A", "B", "C"))
[1] "A, B, C"
str_flatten_comma(c("A", "B", "C"), last = " and ")
[1] "A, B and C"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
49439 次 |
| 最近记录: |