Chirayu Chamoli Chirayu Chamoli - 22 days ago 8
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:

vec1=letters[1:5]
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.

vec1=letters[1:5]
vec3=paste("'", paste(vec1, collapse = "','"), "'", sep = '')
p=paste("select * from df where b in (", vec3, ")")
sqldf(p)


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

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

Answer

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 = "','"))
addQuotes(vec1)
Comments