Search code examples
sqlrregexpastesoql

add single quotes and commas outside the quotes in string


I'd like to take a list of

Ids <- c("00234nisduf", "928347ksjdfn", "92837sdfjkbnfgh")
Ids
[1] "00234nisduf"     "928347ksjdfn"    "92837sdfjkbnfgh"

And turn it into a SOQL query:

Id_Query <- "'00234nisduf', '928347ksjdfn', '92837sdfjkbnfgh'"

The output I'm looking for: '00234nisduf', '928347ksjdfn', '92837sdfjkbnfgh' must have single quotes around each Id and a comma after the quotes for each Id.

I've tried paste(Ids, collapse = ",") and trying to mix with gsub("\\"" "'", Ids) but no luck so far.

Thank you in advance!


Solution

  • Define a function that takes a string and a new string, applies sQuote to its second argument, and uses paste to combine the second argument with the first. Call that function using

    Reduce(your_function, Ids)
    

    EDIT:

    Or, in one line:

    Reduce(function(x,y) paste(x, y, sep=","), sQuote(Ids))