Consider the following:
> n <- 1:4
> n
[1] 1 2 3 4
I would like to transform n
so that I get a string which is '1', '2', '3', '4'
(which in R
, would show as "'1', '2', '3', '4'"
).
This often comes up when I'm using sqlQuery()
with a variable string. I'm not familiar enough with RegEx to be able to perform this operation easily, unfortunately.
The closest I've gotten to is
> paste0(n, collapse = "", sep = ",")
[1] "1,2,3,4,"
which doesn't put the single quotations around each number and has the extra comma at the end.
One option is to use sprintf
with paste0
,
paste0(sprintf("'%d'", 1:4), collapse = ", ")
#[1] "'1', '2', '3', '4'"
where the %d
is the standard formatting flag for signed integers from the C family of formatting functions (printf
, sprintf
, etc.). You can see the various options in the help file (?sprintf
).
I prefer this to other alternatives because the sprintf
call addresses the formatting of individual elements, while the paste0(..., collapse = "<whatever>")
handles the combining of elements; your opinion may differ, though.
I frequently use sprintf
& cat
, in combination with paste0
and other functions, when I need to generate redundant expressions to copy into SQL Server, or generate C++ macros, etc. For example, a bunch of INSERT
statements
cat(sprintf("INSERT INTO #tmp(x, y, z) VALUES('%s', %d, %.2f);",
letters[1:5], 1:5, rnorm(5)),
sep = "\n"
)
#INSERT INTO #tmp(x, y, z) VALUES('a', 1, -1.10);
#INSERT INTO #tmp(x, y, z) VALUES('b', 2, 0.24);
#INSERT INTO #tmp(x, y, z) VALUES('c', 3, -0.82);
#INSERT INTO #tmp(x, y, z) VALUES('d', 4, -0.46);
#INSERT INTO #tmp(x, y, z) VALUES('e', 5, 0.72);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With