开发者

Creating a comma separated vector

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!?


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.


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"


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.


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.


Something similar with toString

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


Just to add on to Noah's answer if you want to use the paste function:

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

Should give you:

[1] '1','2','3','4','5'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜