将值向量转换为逗号分隔的向量,并在每个向量周围引用

时间:2016-09-16 19:39:07

标签: r string paste

我希望得到结果,以便显示为:

  

" 6"" 4"" 8"

或逗号

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

现在我如何获得介于两者之间的逗号?我尝试用sep ='重复这个。但那不起作用。

有什么方法吗?

2 个答案:

答案 0 :(得分:6)

假设输入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"  "\""

答案 1 :(得分:1)

你想要这个吗?

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