runningbirds runningbirds - 2 months ago 9
R Question

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

I'd like to get the result so that it is show as:


"6","4","8"


Or a comma

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


Now how do I get the commas in between? I tried repeating this with the sep = ' but that doesn't work.

Any ways around this?

Answer

Here are a few possibilities assuming input 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 = ", ")

For example,

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

giving:

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

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