Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a comma separated vector

Tags:

r

I have a numeric vector, one, which I'm trying to turn into a character vector where each element is separated by commas.

> one = c(1:5) > paste(as.character(one), collapse=", ") [1] "1, 2, 3, 4, 5" > paste(as.character(one), sep="' '", collapse=", ") [1] "1, 2, 3, 4, 5" 

However, I want the output to look like:

"1", "2", "3", "4", "5"  

Am I missing some parameter from the paste function? Help!?

like image 955
ATMathew Avatar asked Jun 14 '11 17:06

ATMathew


People also ask

What is a comma separated list of vectors?

A comma-separated list is produced for a structure array when you access one field from multiple structure elements at a time. For instance if S is a 5-by-1 structure array then S.name is a five-element comma-separated list of the contents of the name field.

How do you create an array with comma separated Strings?

Use the String. split() method to convert a comma separated string to an array, e.g. const arr = str. split(',') . The split() method will split the string on each occurrence of a comma and will return an array containing the results.


2 Answers

shQuote is probably the best way to do this. Specifically, this gets you the output you want:

cat(paste(shQuote(one, type="cmd"), collapse=", ")) 

If single quotes are fine, you can use:

paste(shQuote(one), collapse=", ") 

type="cmd" actually provides escaped quotes, which is what's actually useful for most contexts, but if you really want to display it somewhere with unescaped quotes, cat provides that.

like image 86
Noah Avatar answered Oct 19 '22 20:10

Noah


You say you want a character vector with that output, but others who find this question may be looking for one of these functions instead:

First, a way to get output ready for input to R; that would be dput:

> dput(as.character(one)) c("1", "2", "3", "4", "5") 

Second, a way to output a csv file, which would be write.csv or write.table. These functions take a parameter file, not used here, to directly output to a file.

> write.table(matrix(as.character(one),nrow=1), sep=",",               row.names=FALSE, col.names=FALSE) "1","2","3","4","5"  > write.csv(matrix(as.character(one),nrow=1),row.names=FALSE) "V1","V2","V3","V4","V5" "1","2","3","4","5" 
like image 33
Aaron left Stack Overflow Avatar answered Oct 19 '22 20:10

Aaron left Stack Overflow