Skip to content

Instantly share code, notes, and snippets.

@obrl-soil
Created November 22, 2016 12:49
Show Gist options
  • Save obrl-soil/a4e7745cb5020accb27d0bbe432d447e to your computer and use it in GitHub Desktop.
Save obrl-soil/a4e7745cb5020accb27d0bbe432d447e to your computer and use it in GitHub Desktop.
some data prep stuff for pushing R variables to SQL queries
# for passing multiple variables to SQL in() queries
ids <- c(1,2,3)
idstring <- paste(ids, collapse=", ")
idstring <- paste0("'", idstring, "'")
#for a string of characters:
idch <- c("1", "2", "3")
idchstring <- paste0("'", idch, "'")
idchstring <- toString(idchstr)
A DBI call would then look like e.g.
qry <- dbGetQuery(con, paste0("select * from table where colname in (", idstring, ")"))
qry <- dbGetQuery(con, paste0("select * from table where colname in (", idchstring, ")"))
# in both cases I usually source the inputs from a data frame column e.g. ids <- df$col
# in that case its generally a good idea to run ids through unique() first
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment