'Concatenate strings with quotation marks separated by commas
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?
Solution 1:[1]
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\""
Solution 2:[2]
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)
Solution 3:[3]
With dQuote
:
v <- c("a", "b", "c")
toString(dQuote(v, q = ""))
#[1] "\"a\", \"b\", \"c\""
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Darren Tsai |
Solution 2 | DaveArmstrong |
Solution 3 | Maël |