Search code examples
rpastequotation-marks

Paste and collapse vector and enclose with quotations


I am trying to formulate a select statement in my API query by pulling a vector from an excel file.

The vector I am pulling from an excel file is:

X <-c("name", "type", "target")

I am then passing this vector into my API query path as such:

path <- paste0(`url`,`table`,"?$select=",paste(`X`, collapse = ","))

and I get the following:

"https://url/api/data/v8.2/table1?$select=name,type,target"

The desired output I want though is to have my select variables enclosed with quotations like this:

"https://url/api/data/v8.2/table1?$select="name","type","target".

However when I try to add quotations in my paste function, like this:

path <- paste0(`url`,`table`,"?$select=",paste('"',`X`,'"', collapse = ","))

I get the following output:

"https://url/api/data/v8.2/table1?$select=\" name \",\" type \",\" target \""

Does anyone know how I can get my desired output with quotations around each selected variable?


Solution

  • We can either use sprintf

    sprintf("https://url/api/data/v8.2/table1?$select='%s','%s','%s'", X[1], X[2], X[3])
    #[1] "https://url/api/data/v8.2/table1?$select='name','type','target'"
    

    If we have 'n' number of elements in 'X'

    s1 <- paste(rep("'%s'", length(X)), collapse=",")
    do.call(sprintf, c(fmt = paste0("https://url/api/data/v8.2/table1?$select=", s1), as.list(X) ))
    #[1] "https://url/api/data/v8.2/table1?$select='name','type','target'"
    

    or glue

    library(glue)
    glue("https://url/api/data/v8.2/table1?$select='{X[1]}','{X[2]}', '{X[3]}'")
    

    In the OP's post, if it is a double quote, it is the escape character. We can check with cat