Querying an SQLite database from R

January 6, 2013

(This article was first published on Will Lowe » R, and kindly contributed to R-bloggers)

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.

To leave a comment for the author, please follow the link and comment on their blog: Will Lowe » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)