TinaW
TinaW

Reputation: 1017

R paste string with collapse - How to keep string with quotes?

I have a problem with the quotes in pasting two strings together.

I want an output like this: query= "sql query","port"

I tried:

      query<-c("sql query","port")
      paste(queryString,collapse=",")

which gives:"sql query,port"

Also tried this:

        query<-c("sql query")
        query<-paste(query,"port",sep=",")

which also gives: "sql query,port"

Without the quotes in the right place the query won't run. How can I keep them ?

Upvotes: 4

Views: 4559

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 270248

Try this:

queryq <- toString(shQuote(query))

which gives:

cat(queryq, "\n")
## "sql query", "port" 

Upvotes: 7

akrun
akrun

Reputation: 887891

You could also use

toString(sprintf("'%s'", query))
#[1] "'sql query', 'port'"

Benchmarks

Created some random strings using stri_rand_strings from stringi

library(stringi)
n <- 1e6
set.seed(25)
query1 <-  stri_rand_strings(n, 6, '[A-Za-z]')

f1 <- function() {toString(sprintf("'%s'", query1)) }
f2 <- function() {toString(shQuote(query1))}

library(microbenchmark)
microbenchmark(f1(), f2(), unit='relative', times=20L)
#Unit: relative
# expr      min       lq    mean   median      uq      max neval cld
#f1() 1.000000 1.000000 1.00000 1.000000 1.00000 1.000000    20  a 
#f2() 1.557221 1.488862 1.43024 1.443488 1.36958 1.362173    20   b

Upvotes: 5

Related Questions