Creating a comma separated vector

Solution 1:

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.

Solution 2:

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"

Solution 3:

Assuming you want your output in a character string (as opposed to a vector of characters) you could try:

paste("'",as.character(one),"'",collapse=", ",sep="")

That gives you single quotes around the numbers rather than double quotes, but it's basically what you seem to want.

And you can always escape to get double quotes:

rs <- paste("\"",as.character(one),"\"",collapse=", ",sep="")
cat(rs)

that should print out what you want with the double quotes.

Solution 4:

In addition to shQuote, see the functions sQuote and dQuote to wrap text in single and double quotes respectively. You'll also want to set options(useFancyQuotes=FALSE) to get plain (unidirectional) ASCII quotes.

Solution 5:

Something similar with toString

toString(paste0("'",1:10,"'") )