Home > Mobile >  Concatenate strings with quotation marks separated by commas
Concatenate strings with quotation marks separated by commas

Time:05-14

I want to write a function that concatenates multiple strings into one one string, but each part is marked with quotation marks and separated by a comma.

The function should basically take the inputs "a"and "b" and print this c('"a", "b"'), which will result in an output like this:

c('"a", "b"')

# [1] "\"a\", \"b\""

How can I created this c('"a", "b"') in a function body?

CodePudding user response:

You can achieve it by a single paste0():

x <- c("a", "b", "c")

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

# [1] "\"a\", \"b\", \"c\""

or sprintf() toString():

toString(sprintf('"%s"', x))
# [1] "\"a\", \"b\", \"c\""

CodePudding user response:

How about this:

x <- c("a", "b")
out <- paste0("c(", paste0('"', x, '"', collapse=", "), ")")
out
#> [1] "c(\"a\", \"b\")"
eval(parse(text=out))
#> [1] "a" "b"

Created on 2022-05-13 by the reprex package (v2.0.1)

CodePudding user response:

With dQuote:

v <- c("a", "b", "c")
toString(dQuote(v, q = ""))
#[1] "\"a\", \"b\", \"c\""
  • Related