Chirayu Chamoli Chirayu Chamoli - 9 months ago 45
R Question

Add single quote to start and end of the vector of a string which would be fed into sqldf

I have vector of string like this:

df=data.frame(a=1:10, b=letters[1:10])

I want to subset this data frame by feeding in the string in sql statement.

vec3=paste("'", paste(vec1, collapse = "','"), "'", sep = '')
p=paste("select * from df where b in (", vec3, ")")

This works well but is there any elegant way to do this task. I tried with
too but it doesnt gives me the desired single quote.

vec3=paste(vec1, collapse = "','")

Answer Source

You can use sprintf for this.

sprintf("'%s'", paste(vec1, collapse = "','"))

create a function will make it more readable...

addQuotes <- function(x) sprintf("'%s'", paste(x, collapse = "','"))