Data is all over the internet. Public CSV files are great for analyzing in R, but to hook into a private business’ data so the can gather statistics on their operation usually has data stored in other methods like a database. R gives a simple library that can allow database connections to source data.
We will show how to do some advanced SQL queries on data used this semester in R. Things that can help get a deeper understanding of your dataset.
This topic is valuable because going beyond the normal selecting and inserting of data into a table, these new functions can help data analysts understand their data
We will be teaching some more advanced SQL topics that can be run in an R program. We will create a sample database and load it with data before diving into the different SQL functions we want to perform on the data and show the results.
Here, we’ll setup some dataframes and load them into a SQLite database table. Normally the database will already exist, but for this demonstration we will build a database with five tables using data from the web.
This is based/expanded on the theory/work/extension of…
A basic example shows how to load data into SQLite database tables and use the SQL language to UNION to join data of a similar structure into one unified table. Here se will use the HMV data for 2000 and 2010 loaded into two seperate tables, and extract the year, and populations
# Create database (in memory)
con <- dbConnect(RSQLite::SQLite(), ":memory:")
# No tables exist
dbListTables(con)## character(0)
# Load MHV data
URL1 <- "https://github.com/DS4PS/cpp-529-fall-2020/raw/main/LABS/data/rodeo/LTDB-2000.rds"
d1 <- readRDS( gzcon( url( URL1 ) ) )
URL2 <- "https://github.com/DS4PS/cpp-529-fall-2020/raw/main/LABS/data/rodeo/LTDB-2010.rds"
d2 <- readRDS( gzcon( url( URL2 ) ) )
dbWriteTable(con, "data00", d1)
dbWriteTable(con, "data10", d2)
# Load 2000 and 2010 data into database tables
new_data00 <- dbGetQuery(con, 'SELECT year, tractid, "pop00.x" as popX, "pop00.y" as popY FROM data00')
new_data10 <- dbGetQuery(con, 'SELECT year, tractid, "pop10.x" as popX, "pop10.y" as popY FROM data00')
dbWriteTable(con, "new_data00", new_data00)
dbWriteTable(con, "new_data10", new_data10)
combined <- dbGetQuery(con, "SELECT * FROM new_data00 UNION SELECT * FROM new_data10")
head(combined)Before we showed how to load several datasets into a SQL table separated by different years and combine them. Now we will go through examples of how to clean up that data and “drop” data from your database after you have processed it.
# here we will have all our old previous tables, we only want the combined source now
dbListTables(con)## [1] "combined" "data00" "data10" "new_data00" "new_data10"
## [1] 0
## [1] 0
## [1] 0
## [1] 0
## [1] "combined"
What’s more, it can also be used for creating new tables that you define in your own model without needing to pull data from the internet. Let’s define a new empty table on what a student model would look like.
dbExecute(con, "CREATE TABLE Student ( \
StudentID INTEGER PRIMARY KEY AUTOINCREMENT, \
FirstName varchar(255),\
LastName varchar(255),\
Address varchar(255),\
City varchar(255),\
State varchar(255))")## [1] 0
## [1] "Student" "combined" "sqlite_sequence"
# and the table will be empty because we didnt insert any data into it yet
student_data <- dbGetQuery(con, "SELECT * FROM Student")
head(student_data)Now with your data model for a student defined you can insert new data you have collected into a SQL table and be able to use all of the tools and features SQL provides to query and modify your dataset
# insert some players salary data
dbExecute(con, "INSERT INTO Student \
(FirstName, LastName, Address, City, State) \
VALUES ('John', 'Doe', '1234 E Street Road', 'Atlanta', 'GA')")## [1] 1
dbExecute(con, "INSERT INTO Student \
(FirstName, LastName, Address, City, State) \
VALUES ('Carl', 'Smith', '3737 N 13th Road', 'Atlanta', 'GA')")## [1] 1
dbExecute(con, "INSERT INTO Student \
(FirstName, LastName, Address, City, State) \
VALUES ('Mary', 'Jane', '5678 N Town Ave', 'San Diego', 'CA')")## [1] 1
dbExecute(con, "INSERT INTO Student \
(FirstName, LastName, Address, City, State) \
VALUES ('Sam', 'Hide', '584990 Farewell Ave', 'San Diego', 'CA')")## [1] 1
dbExecute(con, "INSERT INTO Student \
(FirstName, LastName, Address, City, State) \
VALUES ('Ron', 'Old', '29 E Unit 1', 'Phoenix', 'AZ')")## [1] 1
# Now show the inserted data for 2024
GA_STUDENTS <- dbGetQuery(con, "SELECT * \
FROM Student \
WHERE State = 'GA'")
head(GA_STUDENTS)R provides many useful packages for interacting with existing or new databases. This can allow you to define your own data in an easy to process tool like SQL. being able to not only consume others data, but also define your own is extremely useful when publishing data to the internet for research
Learn more about RSQLite with the following:
This code through references and cites the following sources:
Arias (2019). DataCamp. SQLite in R
Kirill Müller. DBI for R. SQLite Interface for R
SQLite Tutorial SQLite AUTOINCREMENT