Clarinetist
Clarinetist

Reputation: 1197

Put quotation marks around each element of a vector, and separate with comma

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.

Upvotes: 11

Views: 6897

Answers (2)

coip
coip

Reputation: 1520

If you're just looking to print, you can do this using cat() with a comma separator in conjunction with either dQuote() for double quotation marks or sQuote() for single quotation marks:

n <- 1:4
cat(dQuote(n), sep = ",")
cat(sQuote(n), sep = ",")

If you're looking to store as an object, you can swap out cat() for paste():

d <- paste(dQuote(n), collapse = ",")
s <- paste(sQuote(n), collapse = ",")

Upvotes: 1

nrussell
nrussell

Reputation: 18612

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);

Upvotes: 11

Related Questions