Querying an SQLite database from R

You have an SQLite database, perhaps as part of some replication materials, and you want to query it from R. You might want to be able to say:

results <- runsql("select * from mytable order by date")

and get the results back as an R object. Here’s a function to do it.

In the following, I’m going to assume the database is called mydatabase.db.

First install the {RSQLite} package if you don’t have it already. Then the following function does what’s wanted:

runsql <- function(sql, dbname = "mydatabase.db") {
  driver <- dbDriver("SQLite")
  connect <- dbConnect(driver, dbname = dbname);
  closeup <- function(){
  dd <- tryCatch(dbGetQuery(connect, sql),
                 finally = closeup)

This code loads a driver, opens a connection, runs the query and closes the connection whether or not it is successful. If efficiency were a concern you’d want to run a bunch of queries on the same connection. All the functions you’d need for that are above.

Also, this is pretty low level interface so you may need to add types to your results

results <- transform(results, d1 = as.Date(d1))

Actually dates are a little bit quirky in SQLite, but that’s a post for another day.

If you found this helpful...

ko-fi page


This page has an open-source license (Creative Commons BY-NC-ND)

Creative Commons License BY-NC-ND