Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 299
userJT Avatar asked Feb 16 '12 15:02

userJT


People also ask

What does Str_c do in R?

str_c: Join multiple strings into a single string. Joins two or more vectors element-wise into a single character vector, optionally inserting sep between input vectors. If collapse is not NULL , it will be inserted between elements of the result, returning a character vector of length 1.

How do I convert a list to a vector in R?

Converting a List to Vector in R Language – unlist() Function. unlist() function in R Language is used to convert a list to vector. It simplifies to produce a vector by preserving all components.

What does paste0 mean in R?

In R, the paste0() function is used to concatenate vectors after converting to character vectors.

How do I make a list of strings in R?

How to Create Lists in R? We can use the list() function to create a list. Another way to create a list is to use the c() function. The c() function coerces elements into the same type, so, if there is a list amongst the elements, then all elements are turned into components of a list.


2 Answers

You can do it with paste function

    > paste(c('A', 'B', 'C'), collapse=', ' )     [1] "A, B, C" 
like image 137
ilya Avatar answered Sep 30 '22 12:09

ilya


You can do it with str_c function

> library('stringr') > str_c(c('A','B','C'),collapse=',')     [1] "A,B,C" 
like image 37
Chernoff Avatar answered Sep 30 '22 13:09

Chernoff