The Wayback Machine - https://web.archive.org/web/20240927120802/https://www.geeksforgeeks.org/manipulate-r-data-frames-using-sql/
Open In App

Manipulate R Data Frames Using SQL

Last Updated : 04 Aug, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Manipulating data frames in R Programming using SQL can be easily done using the sqldf package. This package in R provides a mechanism that allows data frame manipulation with SQL and also helps to connect with a limited number of databases. The sqldf package in R is basically used for executing the SQL commands or statements on data frames. One can simply specify the SQL statement using data frame names instead of table names in R, and then the following things happen: 
 

  • A database with proper schema or table layout is created
  • The data frames are loaded into the created database automatically
  • The specific SQL statement or command is executed
  • The result is retrieved back into R, and
  • Automatically the database gets deleted.

This makes the existence of the database quite transparent. This method can lead to faster R calculation. The result is obtained using some heuristics in order to determine the class which is to be assigned to each column of the resultant data frame.
 

Working With sqldf in R

A handful of SQL operations can be performed in R using the sqldf package. Let’s use two csv files from the Highway data. 
 

  • crashes.csv which contains Year, Road, N_Crashes, and Volume.
  • roads.csv which contains Road, District, and Length.

In order to work with the sqldf package, first install it as follows: 
 

install.packages("sqldf")

After proper installation, include the package in R script as follows: 
 

library(sqldf)

Now load the data in the script. In order to do so, change the present directory to the directory which contains the csv files crashes.csv and roads.csv using the setwd() function. 
Example: 
 

r




# Importing required library
library(sqldf)
 
# Changing the directory
setwd("C:\\Users\\SHAONI\\Documents\\
                     R\\win-library")
 
# Reading the csv files
crashes <- read.csv("crashes.csv")
roads <- read.csv("roads.csv")
 
# Displaying the data in crashes.csv
head(crashes)
tail(crashes)
 
# Displaying the data in roads.csv
print(roads)


Output: 
 

  Year     Road       N_Crashes Volume
1 1991 Interstate 65        25  40000
2 1992 Interstate 65        37  41000
3 1993 Interstate 65        45  45000
4 1994 Interstate 65        46  45600
5 1995 Interstate 65        46  49000
6 1996 Interstate 65        59  51000

    Year  Road           N_Crashes Volume
105 2007 Interstate 275        32  21900
106 2008 Interstate 275        21  21850
107 2009 Interstate 275        25  22100
108 2010 Interstate 275        24  21500
109 2011 Interstate 275        23  20300
110 2012 Interstate 275        22  21200

           Road       District   Length
1 Interstate 65     Greenfield    262
2 Interstate 70      Vincennes    156
3         US-36 Crawfordsville    139
4         US-40     Greenfield    150
5         US-52 Crawfordsville    172

Now perform any SQL operation on these data using the sqldf() function of the sqldf package.
 

Joining and Merging Data Frames

The most common SQL operation is the join operation. One can perform left join and inner join using sqldf(). Currently, sqldf() does not support the full outer join and right join operations. Along with the sqldf package we need to include the tcltk package.
Example 1: Performing left join operation
 

r




# Perform Left Join
 
# Importing required library
library(sqldf)
library(tcltk)
 
# Setting the directory
setwd("C:\\Users\\SHAONI\\Documents\\
                     R\\win-library")
 
# Reading the csv files
crashes <- read.csv("crashes.csv")
roads <- read.csv("roads.csv")
 
# Performing left join
join_string <- "select crashes.*,
                 roads.District,
                 roads.Length
                 from crashes
                 left join
                 roads on
                 crashes.Road = roads.Road"
 
# Resultant data frame
crashes_join_roads <- sqldf(join_string,
                stringsAsFactors = FALSE)
head(crashes_join_roads)
tail(crashes_join_roads)


Output: 
 

  Year    Road        N_Crashes Volume  District   Length
1 1991 Interstate 65        25  40000 Greenfield    262
2 1992 Interstate 65        37  41000 Greenfield    262
3 1993 Interstate 65        45  45000 Greenfield    262
4 1994 Interstate 65        46  45600 Greenfield    262
5 1995 Interstate 65        46  49000 Greenfield    262
6 1996 Interstate 65        59  51000 Greenfield    262

    Year  Road          N_Crashes Volume     District     Length
105 2007 Interstate 275        32  21900     <NA>     NA
106 2008 Interstate 275        21  21850     <NA>     NA
107 2009 Interstate 275        25  22100     <NA>     NA
108 2010 Interstate 275        24  21500     <NA>     NA
109 2011 Interstate 275        23  20300     <NA>     NA
110 2012 Interstate 275        22  21200     <NA>     NA

Explanation: 
The crashes_join_roads is a new data frame created by the sqldf statement which stores the result of the join operation. The sqldf() function or operation requires at least a string character along with the SQL operation. The stringsAsFactors parameter is used to assign character class to the categorical data instead of factor class.
Example 2: Performing inner join 
 

r




# Perform Inner Join
 
# Importing required package
library(sqldf)
library(tcltk)
 
# Selecting the proper directory
setwd("C:\\Users\\SHAONI\\Documents\\
                     R\\win-library")
# Reading the csv files
crashes <- read.csv("crashes.csv")
roads <- read.csv("roads.csv")
 
# Performing the inner join
join_string2 <- "select crashes.*,
                 roads.District,
                 roads.Length
                 from crashes
                 inner join
                 roads on
                 crashes.Road = roads.Road"
 
# The new data frame
crashes_join_roads2 <- sqldf(join_string2,
                 stringsAsFactors = FALSE)
head(crashes_join_roads2)
tail(crashes_join_roads2)


Output: 
 

 
  Year     Road       N_Crashes Volume  District  Length
1 1991 Interstate 65        25  40000 Greenfield    262
2 1992 Interstate 65        37  41000 Greenfield    262
3 1993 Interstate 65        45  45000 Greenfield    262
4 1994 Interstate 65        46  45600 Greenfield    262
5 1995 Interstate 65        46  49000 Greenfield    262
6 1996 Interstate 65        59  51000 Greenfield    262

   Year  Road  N_Crashes Volume   District      Length
83 2007 US-36        49  24000 Crawfordsville    139
84 2008 US-36        52  24500 Crawfordsville    139
85 2009 US-36        55  24700 Crawfordsville    139
86 2010 US-36        35  23000 Crawfordsville    139
87 2011 US-36        33  21000 Crawfordsville    139
88 2012 US-36        31  20500 Crawfordsville    139

Here only the matching rows are kept in the resultant data frame.
Now let’s see how the merge() function works. In R, the merge operation is capable of performing left join, right join, inner join, and full outer join, unlike the sqldf() function. Also, one can easily perform the equivalent operation like sqldf() using the merge() operation.
Example 3: 
 

r




# Perform Merge operation
 
# Import required library
library(sqldf)
library(tcltk)
 
setwd("C:\\Users\\SHAONI\\Documents\\
                     R\\win-library")
 
# Reading the two csv files
crashes <- read.csv("crashes.csv")
roads <- read.csv("roads.csv")
# Merge the two data frames
crashes_merge_roads2 <- merge(crashes,
                              roads,
                              by = c("Road"),
                              all.x = TRUE)
head(crashes_merge_roads2)
tail(crashes_merge_roads2)


Output: 
 

 
     Road        Year  N_Crashes Volume    District    Length
1 Interstate 275 1994        21  21200     <NA>     NA
2 Interstate 275 1995        28  23200     <NA>     NA
3 Interstate 275 1996        22  20000     <NA>     NA
4 Interstate 275 1997        27  18000     <NA>     NA
5 Interstate 275 1998        21  19500     <NA>     NA
6 Interstate 275 1999        22  21000     <NA>     NA

     Road Year N_Crashes Volume   District  Length
105 US-40 2003        94  55200 Greenfield    150
106 US-40 2004        25  55300 Greenfield    150
107 US-40 2009        67  65000 Greenfield    150
108 US-40 2010       102  67000 Greenfield    150
109 US-40 2011        87  67500 Greenfield    150
110 US-40 2012        32  67500 Greenfield    150

We will see that the rows in the resultant data frames are rearranged when we are using the merge() function.
 

Using where Clause

R can perform the exact operations as SQL. Hence to use a SQL statement where to include any condition use the where clause.
Example: 
Let’s see how to perform inner join using the combination of merge and subset operation by including the where clause in the query.
 

r




# Using where clause
 
# Importing required library
library(sqldf)
library(plyr)
library(tcltk)
 
setwd("C:\\Users\\SHAONI\\Documents\\
                     R\\win-library")
crashes <- read.csv("crashes.csv")
roads <- read.csv("roads.csv")
 
# Using the where clause
join_string2 <- "select crashes.*,
                 roads.District,
                 roads.Length
                 from crashes
                 inner join
                 roads on
                 crashes.Road = roads.Road
                 where
                 crashes.Road = 'US-40'" 
               
crashes_join_roads4 <- sqldf(join_string2,
                 stringsAsFactors = FALSE)
head(crashes_join_roads4)
tail(crashes_join_roads4)


Output: 
 

  Year  Road  N_Crashes Volume District   Length
1 1991 US-40        46  21000 Greenfield    150
2 1992 US-40       101  21500 Greenfield    150
3 1993 US-40        76  23000 Greenfield    150
4 1994 US-40        72  21000 Greenfield    150
5 1995 US-40        75  24000 Greenfield    150
6 1996 US-40       136  23500 Greenfield    150

   Year  Road N_Crashes  Volume  District  Length
17 2007 US-40        45  59500 Greenfield    150
18 2008 US-40        23  61000 Greenfield    150
19 2009 US-40        67  65000 Greenfield    150
20 2010 US-40       102  67000 Greenfield    150
21 2011 US-40        87  67500 Greenfield    150
22 2012 US-40        32  67500 Greenfield    150

 

Aggregate Functions

In the sqldf package, the aggregate operations can be performed using the group by clause.
Example: 
 

r




# Perform aggregate operations
 
# Import required library
library(sqldf)
library(tcltk)
 
setwd("C:\\Users\\SHAONI\\Documents\\
                     R\\win-library")
crashes <- read.csv("crashes.csv")
roads <- read.csv("roads.csv")
 
# Group by clause
group_string <- "select crashes.Road,
                 avg(crashes.N_Crashes)
                 as Mean_Crashes
                 from crashes
                 left join
                 roads on
                 crashes.Road = roads.Road
                 group by 1"
sqldf(group_string)


Output: 
 

      Road         Mean_Crashes
1 Interstate 275     24.95455
2  Interstate 65    107.81818
3  Interstate 70     65.18182
4          US-36     48.00000
5          US-40     68.68182

The sqldf() function can be used for performing certain kinds of data manipulations. To overcome these limitations, use the plyr package in the R Script. Hadley Wickham’s plyr package can be used to perform advanced calculations and data manipulations. Let’s see how it works.
Example: 
 

r




# Importing required library
library(sqldf)
library(plyr)
library(tcltk)
 
setwd("C:\\Users\\SHAONI\\Documents\\
                     R\\win-library")
crashes <- read.csv("crashes.csv")
roads <- read.csv("roads.csv")
 
ddply(
crashes_merge_roads,
c("Road"),
function(X)
data.frame(
  Mean_Crashes = mean(X$N_Crashes),
  Q1_Crashes = quantile(X$N_Crashes, 0.25),
  Q3_Crashes = quantile(X$N_Crashes, 0.75),
  Median_Crashes = quantile(X$N_Crashes, 0.50))
)


Output: 
 

 
     Road        Mean_Crashes   Q1_Crashes Q3_Crashes   Median_Crashes
1 Interstate 65    107.81818      63.25     140.25          108.5
2 Interstate 70     65.18182      52.00      75.50           66.5
3         US-36     48.00000      42.00      57.25           47.0
4         US-40     68.68182      45.25      90.75           70.0

 



Similar Reads

How to build a function that loops through data frames and transforms the data in R?
Working with multiple data frames in R can often require repetitive tasks. Automating these tasks with a function can save time and reduce errors. This article will guide you through building a function in R that loops through multiple data frames and applies transformations to them. What is transformation?In R, the term "transformed" often refers
3 min read
Merge Several Data Frames into One Data Frame with a Loop in R
Merging several data frames into one is a common task in data analysis. Suppose you have multiple data frames with similar structures and you want to combine them into a single data frame. In that case, you can do this efficiently using a loop in R. This approach is beneficial when dealing with many data frames. Merge Several Data FramesIn R Langua
4 min read
Subset Data Frames Using Logical Conditions In R
In this article, we will explore various methods of Subset data frames using logical conditions using the R Programming Language. How to Subset data frames using logical conditionsR language offers various methods to subset data frames using logical conditions. By using these methods provided by R, it is possible to subset a data frame. Some of the
3 min read
Comparing values of data frames in R Programming - all_equal() Function
all_equal() function in R Language is used to compare the values between dataframes. Syntax: all_equal(target, current, check.attributes, check.names) Parameters: target: object to comparecurrent: object to be compared withcheck.attributes: If attributes of both be comparedcheck.names: If names be comparedR - compare values of data frames Example 1
2 min read
Combine Vectors, Matrix or Data Frames by Columns in R Language - cbind() Function
cbind() function in R Language is used to combine specified Vector, Matrix or Data Frame by columns. Syntax: cbind(x1, x2, ..., deparse.level = 1) Parameters: x1, x2: vector, matrix, data frames deparse.level: This value determines how the column names generated. The default value of deparse.level is 1. Example 1: # R program to illustrate # cbind
2 min read
Merge Two Data Frames by common Columns in R Programming - merge() Function
merge() function in R Language is used to merge two data frames by common columns. Syntax: merge(arg1, arg2, by.x, by.y) Parameters: arg1 and arg2: Data frames to be merged by.x: Common argument of first data frame by.y: Common argument of second data frame Example 1: # R program to merge two data frames # Creating data frames df1 <- data.frame(
1 min read
R - Data Frames
R Programming Language is an open-source programming language that is widely used as a statistical software and data analysis tool. Data Frames in R Language are generic data objects of R that are used to store tabular data.  Data frames can also be interpreted as matrices where each column of a matrix can be of different data types. R DataFrame is
10 min read
Combine Vectors, Matrix or Data Frames by Rows in R Language - rbind() Function
In this article, we will discuss how we Combine Vectors, Matrices, or Data Frames by Rows in R Programming Language using rbind function. What is rbind function?The rbind function combines or concatenates data frames or matrices by rows. the rbind stands for row binds it shows that it appends rows of one object to another. Syntax: rbind(x1, x2, ...
3 min read
Indexing and Slicing Data Frames in R
In this article let's discuss indexing and slicing the Data Frames or how to access elements of a data frame in R Programming Language. What is Indexing or accessing?The process of accessing particular data components or subsets within a vector, matrix, or data frame is called indexing. It enables us to pick, remove, or change particular values or
4 min read
Get and Set Row Names for Data Frames
In this article, we will explore various methods to Get and Set row names for Data Frames in R Programming Language. What is Data Frames?Dataframes are the 2- dimensional data structure which organizes the data into rows and columns. These data frames are commonly used for manipulation, analysis, and visualization of data efficiently. Dataframes ca
5 min read
How to Manipulate MySQL Storage Engines?
MySQL DBMS offers a wide range of storage engines which are basically software modules used to perform actions like CREATE, INSERT, READ and DELETE in DBMS. Depending upon the user's requirement, we can access various storage engines for MySQL DBMS. For MySQL 5.5 and later versions, the default storage engine is InnoDB.It is necessary to choose the
2 min read
How to manipulate ggplot2 facet grid text size in R ?
In this article, we will be looking at the approach to change the size of the facet grid text size from the ggplot2 package in the R programming language. We will use the theme() function, further with the strip.text.x = element_text(size) argument of this function, the user needs to enter the value of the size required as per the user demand, here
2 min read
Configure SQL Jobs in SQL Server using T-SQL
In this article, we will learn how to configure SQL jobs in SQL Server using T-SQL. Also, we will discuss the parameters of SQL jobs in SQL Server using T-SQL in detail. Let's discuss it one by one. Introduction :SQL Server Agent is a component used for database task automation. For Example, If we need to perform index maintenance on Production ser
7 min read
Difference between Structured Query Language (SQL) and Transact-SQL (T-SQL)
Structured Query Language (SQL): Structured Query Language (SQL) has a specific design motive for defining, accessing and changement of data. It is considered as non-procedural, In that case the important elements and its results are first specified without taking care of the how they are computed. It is implemented over the database which is drive
2 min read
How to SQL Select from Stored Procedure using SQL Server?
There may be situations in SQL Server where you need to use a stored procedure to get data from a SQL query. For direct data selection from a stored procedure within a query, SQL Server offers options like OPENQUERY and OPENROWSET. The usual way is running the stored procedure independently and then querying the outcomes. The idea of utilizing SQL
3 min read
How to Convert Data From SQL to C Data Types?
At the point when an application calls SQLExecute or SQLExecDirect, the driver recovers the data for any boundaries bound with SQLBindParameter from capacity areas in the application. At the point when an application calls SQLSetPos, the driver recovers the data for an update or adds activity from sections bound with SQLBindCol. For data-at-executi
6 min read
SQL SERVER – Input and Output Parameter For Dynamic SQL
An Input Parameter can influence the subset of rows it returns from a select statement within it. A calling script can get the value of an output parameter. An aggregate function or any computational expression within the stored process can be used to determine the value of the output parameter. A parameter whose value is given into a stored proced
3 min read
Difference between T-SQL and PL-SQL
1. Transact SQL (T-SQL) : T-SQL is an abbreviation for Transact Structure Query Language. It is a product by Microsoft and is an extension of SQL Language which is used to interact with relational databases. It is considered to perform best with Microsoft SQL servers. T-SQL statements are used to perform the transactions to the databases. T-SQL has
3 min read
SQL Server | Convert tables in T-SQL into XML
In this, we will focus on how tables will be converted in T-SQL into XML in SQL server. And you will be able to understand how you can convert it with the help of command. Let's discuss it one by one. Overview :XML (Extensible Markup Language) is a markup language similar to HTML which was designed to share information between different platforms.
2 min read
SQL - SELECT from Multiple Tables with MS SQL Server
In SQL we can retrieve data from multiple tables also by using SELECT with multiple tables which actually results in CROSS JOIN of all the tables. The resulting table occurring from CROSS JOIN of two contains all the row combinations of the 2nd table which is a Cartesian product of tables. If we consider table1 contains m rows and table2 contains n
3 min read
How to Execute SQL Server Stored Procedure in SQL Developer?
A stored procedure is a set of (T-SQL ) statements needed in times when we are having the repetitive usage of the same query. When there is a need to use a large query multiple times we can create a stored procedure once and execute the same wherever needed instead of writing the whole query again. In this article let us see how to execute SQL Serv
2 min read
SQL Query to Check if Date is Greater Than Today in SQL
In this article, we will see the SQL query to check if DATE is greater than today's date by comparing date with today's date using the GETDATE() function. This function in SQL Server is used to return the present date and time of the database system in a ‘YYYY-MM-DD hh:mm: ss. mmm’ pattern. Features: This function is used to find the present date a
2 min read
SQL Query to Add a New Column After an Existing Column in SQL
Structured Query Language or SQL is a standard Database language that is used to create, maintain and retrieve data from relational databases like MySQL, Oracle, SQL Server, Postgres, etc. In Microsoft SQL Server, we can change the order of the columns and can add a new column by using ALTER command. ALTER TABLE is used to add, delete/drop or modif
3 min read
SQL Query to Convert Rows to Columns in SQL Server
In this article we will see, how to convert Rows to Column in SQL Server. In a table where many columns have the have same data for many entries in the table, it is advisable to convert the rows to column. This will help to reduce the table and make the table more readable. For example, Suppose we have a table given below: NAMECOLLEGEROLL NUMBERSUB
2 min read
SQL Quiz : Practice SQL Questions Online
This SQL quiz covers various topics like SQL basics, CRUD operations, operators, aggregation functions, constraints, joins, indexes, transactions, and query-based scenarios. We've included multiple-choice questions, fill-in-the-blank questions, and interactive coding challenges to keep things interesting and challenging. Whether you're a beginner l
3 min read
BULK INSERT in SQL Server(T-SQL command)
BULK INSERT in SQL Server(T-SQL command): In this article, we will cover bulk insert data from csv file using the T-SQL command in the SQL server and the way it is more useful and more convenient to perform such kind of operations. Let's discuss it one by one.  ConditionSometimes there is a scenario when we have to perform bulk insert data from .cs
3 min read
SQL Exercises : SQL Practice with Solution for Beginners and Experienced
SQL (Structured Query Language) is a powerful tool used for managing and manipulating relational databases. Whether we are beginners or experienced professionals, practicing SQL exercises is important for improving your skills. Regular practice helps you get better at using SQL and boosts your confidence in handling different database tasks. So, in
15+ min read
Difference between SQL and T-SQL
SQL (Structured Query Language) is the standard language for managing and manipulating relational databases, enabling operations like querying, updating, and deleting data. T-SQL (Transact-SQL), an extension of SQL developed by Microsoft, adds advanced features and procedural capabilities specifically for SQL Server. In this article, We will learn
4 min read
SQL using Python | Set 3 (Handling large data)
It is recommended to go through SQL using Python | Set 1 and SQL using Python and SQLite | Set 2 In the previous articles the records of the database were limited to small size and single tuple. This article will explain how to write & fetch large data from the database using module SQLite3 covering all exceptions. A simple way is to execute th
4 min read
SQL | Checking Existing Constraints on a Table using Data Dictionaries
Prerequisite: SQL-Constraints In SQL Server the data dictionary is a set of database tables used to store information about a database's definition. One can use these data dictionaries to check the constraints on an already existing table and to change them(if possible). USER_CONSTRAINTS Data Dictionary: This data dictionary contains information ab
2 min read
Article Tags :