Search code examples
rsqliteimport

How to read the content of a .db file in R?


This is the first time I am trying to load this type of file in R and for whatever reason it's been quite challenging.

The data I am using can be found here.

So, I am following instructions from a book that teaches about survey data, and the book uses this data as example. However, there are no instructions about how to load the data in R. The data is in SQLite format, which is a bit odd to me.

With a little research I came into this post, which was the closest to my problem. When I try to apply the code provided I run into error.

library(RSQLite)
filename <- dbConnect(SQLite(), dbname = 'imp.db')

sqlite.driver <- dbDriver("SQLite")
db <- dbConnect(sqlite.driver,
                dbname = filename)

And I run into the following error:

Error in as.character.default(x) : 
  no method for coercing this S4 class to a vector
In addition: Warning message:
In is.na(dbname) : is.na() applied to non-(list or vector) of type 'S4'

All I wanna do is to load the content as a data.frame or any other format that is used in R. Can someone help me?


Solution

  • Next, I try to run the code test <- svydesign(id=~SDPPSUG, + strat = ~SDPSTRAG, + weigh = ~WTPFQXG, + nest = T, + data = db)

    From ?survey::svydesign:

    data may be a character string giving the name of a table or view in a relational database that can be accessed through the DBI interfaces. For DBI interfaces dbtype should be the name of the database driver and dbname should be the name by which the driver identifies the specific database (eg file name for SQLite).

    Based on the database example from svydesign documentation, you could try:

    library(survey, warn.conflicts = FALSE)
    #> Loading required package: grid
    #> Loading required package: Matrix
    #> Loading required package: survival
    library(RSQLite)
    
    test <- svydesign(id=~SDPPSU6, strat = ~SDPSTRA6, weight = ~WTPFQX6, nest = TRUE, 
                      data = "set1", dbtype="SQLite", dbname = "imp.db") 
    test
    #> DB-backed Stratified 1 - level Cluster Sampling design (with replacement)
    #> With (98) clusters.
    #> svydesign(id = ~SDPPSU6, strat = ~SDPSTRA6, weight = ~WTPFQX6, 
    #>     nest = TRUE, data = "set1", dbtype = "SQLite", dbname = "imp.db")
    close(test)
    

    Created on 2024-09-21 with reprex v2.1.1