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

4

67

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.

Cordage answered 16/2, 2012 at 15:46 Comment(1)
You're talking about lists of characters (you're even subsetting via [[). If d is a list of characters, you can also do.call("paste", c(d, sep = " | ")).Jehovah
J
90

You can do it with paste function

    > paste(c('A', 'B', 'C'), collapse=', ' )
    [1] "A, B, C"
Jacal answered 16/2, 2012 at 15:51 Comment(0)
S
14

You can do it with str_c function

> library('stringr')
> str_c(c('A','B','C'),collapse=',')    
[1] "A,B,C"
Stotts answered 12/3, 2014 at 18:29 Comment(0)
W
9

The shortest method is to use the base toString function. In any case the output string will contain commas

vector<-c('A', 'B', 'C')

toString(vector)

if you don't want commas

gsub(",","",toString(vector))

If you want any other separator you can substitute anything you like in gsub instead of replacing commas with nothing

Wentzel answered 24/8, 2020 at 14:50 Comment(0)
Q
5

Also from stringr is the str_flatten function:

library(stringr)

str_flatten(c("A", "B", "C"), ",")
[1] "A,B,C"

stringr 1.5.0 added 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"
Quag answered 10/11, 2021 at 0:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.