将值的向量转换为逗号分隔的向量,每个向量都用引号括起来

Turning a vector of values into a comma separated vector with quote around each

我想要得到的结果显示为:

"6","4","8"

或逗号

my_vector = base::unique(mtcars$cyl)
my_vector_quoted =paste(my_vector, sep=" ' ")

现在如何获取中间的逗号?我尝试用 sep = ' 重复此操作,但这不起作用。

有什么解决办法吗?

你想要这个吗?

my_vector_quoted =paste(my_vector, collapse=",")
#"6,4,8"

这里有一些假设输入 x:

的可能性
toString(shQuote(x, type = "cmd"))

options(useFancyQuotes = FALSE)
toString(dQuote(x))

library(withr)
with_options(c(useFancyQuotes = FALSE), toString(dQuote(x)))

toString(sprintf('"%d"', x))

paste(paste0('"', x, '"'), collapse = ", ")

例如,

x <- c(6, 4, 8)
xs <- toString(shQuote(x, type = "cmd"))

给予:

> cat(xs, "\n")
"6", "4", "8" 

> strsplit(xs, "")[[1]] # shows that xs contains 13 characters
[1] "\"" "6"  "\"" ","  " "  "\"" "4"  "\"" ","  " "  "\"" "8"  "\""