创建一个逗号分隔的向量

我有一个数值向量,我要把它变成一个字符向量 每个元素用逗号分隔。

> 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"

但是,我希望输出看起来像:

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

我是否遗漏了粘贴函数中的某些参数? 救命! ?

109766 次浏览

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.

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"

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.

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'

Something similar with toString

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