The Wayback Machine - https://web.archive.org/web/20240723122657/https://www.geeksforgeeks.org/working-with-databases-in-r-programming/
Open In App

Working with Databases in R Programming

Last Updated : 25 Nov, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Prerequisite: Database Connectivity with R Programming

In R programming Language, a number of datasets are passed to the functions to visualize them using statistical computing. So, rather than creating datasets again and again in the console, we can pass those normalized datasets from relational databases.

Databases in R Programming Language

R can be connected to many relational databases such as Oracle, MySQL, SQL Server, etc, and fetches the result as a data frame. Once the result set is fetched into data frame, it becomes very easy to visualize and manipulate them. In this article, we’ll discuss MySQl as reference to connect with R, creating, dropping, inserting, updating, and querying the table using R Language.

RMySQL Package

It is a built-in package in R and Its provides connectivity between the R and MySql databases. It can be installed with the following commands:

install.packages("RMySQL")

Connecting MySQL with R Programming Language

R requires RMySQL package to create a connection object which takes username, password, hostname and database name while calling the function. dbConnect() function is used to create the connection object in R.

Syntax: dbConnect(drv, user, password, dbname, host)
Parameter values: 

  • drv represents Database Driver
  • user represents username
  • password represents password value assigned to Database server
  • dbname represents name of the database
  • host represents host name

Example:

R




# Install package
install.packages("RMySQL")
 
# Loading library
library("RMySQL")
 
# Create connection
mysqlconn = dbConnect(MySQL(), user = 'root', password = 'welcome',
                      dbname = 'GFG', host = 'localhost')
 
# Show tables in database
dbListTables(mysqlconn)


Tables present in the given database: 

Output: 

Loading required package: DBI
[1] "articles"

Create Tables in MySQL Using R

Tables in MySQL can be created using function dbWriteTable() in R. This function overwrites the table if table already exists.

Syntax: dbWriteTable(conn, name, value)

Parameter value: 

  • conn represents connection object
  • name represents name of the table in MySQL
  • value represents dataframe that has to be presented as MySQL table

Example: 

R




# Create connection object
mysqlconn = dbConnect(MySQL(), user = 'root',
                      password = 'welcome',
                      dbname = 'GFG',
                      host = 'localhost')
 
# Create new table mtcars
dbWriteTable(mysqlconn, "mtcars",
             mtcars[1:10, ],
             overwrite = TRUE)


Output: 

[1] TRUE

Database table content: 

Drop Tables in MySQL Using R

To perform other operations than creating table, dbSendQuery() function is used to execute a query.

Syntax: dbSendQuery(conn, statement)

Parameter values: 

  • conn represents connection object
  • statement represents query to be executed in MySQL

Example: 

R




# Create connection object
mysqlconn = dbConnect(MySQL(), user = 'root',
                      password = 'welcome',
                      dbname = 'GFG',
                      host = 'localhost')
 
# Drop table mtcars from database
dbSendQuery(mysqlconn, 'DROP TABLE mtcars')


Output: 

<MySQLResult:745348760, 3, 5>

Database content:

Insert into Table in MySQL Using R

Here we are going to insert a value into a table.

Example: 

R




# Create connection object
mysqlconn = dbConnect(MySQL(), user = 'root',
                      password = 'welcome',
                      dbname = 'GFG', host = 'localhost')
 
# Inserting into articles table
dbSendQuery(mysqlconn, "insert into articles(sno, type)
values(1, 'R language')"
)


Output: 

<MySQLResult:745348760, 3, 6>

Database content: 

Updating a Table in MySQL Using R

Here we are going to update table in Mysql.

Example: 

R




# Create connection object
mysqlconn = dbConnect(MySQL(), user = 'root',
                      password = 'welcome',
                      dbname = 'GFG', host = 'localhost')
 
# Update query
dbSendQuery(mysqlconn, "UPDATE articles SET sno = 10 \
where type = 'R language'")


Output: 

<MySQLResult:-1, 3, 7>

Database content:

Querying a Table in MySQL Using R

Here we are going to see how to use query in table.

Example: 

R




# Create connection object
mysqlconn = dbConnect(MySQL(), user = 'root',
                      password = 'welcome',
                      dbname = 'GFG', host = 'localhost')
 
# Select all rows from articles table
res = dbSendQuery(mysqlconn, "SELECT *FROM articles")
 
# Fetch first 3 rows in data frame
df = fetch(res, n = 3)
print(df)


Output: 

  sno       type
1   1 Data Struc
2   2       Algo
3   3       Java

Database content:



Previous Article
Next Article

Similar Reads

Working with databases and SQL in RStudio
In today’s data-driven world, the interface between SQL (Structured Query Language) and R has become a must-have for data professionals. SQL empowers us to efficiently interact with relational databases, while R programming language is versatile for data analysis. Combining these two powerful tools can dramatically increase your data conversion cap
9 min read
10 Best Databases for Machine Learning and AI [2024]
Machine learning and Artificial Intelligence are the two trending fields in the IT industries that involve a lot of technologies. Hence, databases are the main things which are used in Machine learning and Artificial Intelligence and they serve as a basic foundation for these trending technologies. They also developed their predictive and decision-
7 min read
Working with XML Files in R Programming
XML which stands for Extensible Markup Language is made up of markup tags, wherein each tag illustrates the information carried by the particular attribute in the XML file. We can work with the XML files using the XML package provided by R. The package has to be explicitly installed using the following command: install.packages("XML")Creating XML f
3 min read
Working with Excel Files in R Programming
Excel files are of extension .xls, .xlsx and .csv(comma-separated values). To start working with excel files in R Programming Language, we need to first import excel files in RStudio or any other R supporting IDE(Integrated development environment). Reading Excel Files in R Programming Language First, install readxl package in R to load excel files
3 min read
Working with Binary Files in R Programming
In the computer science world, text files contain data that can easily be understood by humans. It includes letters, numbers, and other characters. On the other hand, binary files contain 1s and 0s that only computers can interpret. The information stored in a binary file can't be read by humans as the bytes in it translate to characters and symbol
5 min read
List all the Objects present in the Current Working Directory in R Programming - ls() Function
ls() function in R Language is used to list the names of all the objects that are present in the working directory. Syntax: ls() Parameters: This function needs no argument Example 1: # R program to list all the object names # Creating a vector vec &lt;- c(1, 2, 3) # Creating a matrix mat &lt;- matrix(c(1:4), 2) # Creating an array arr &lt;- array(
1 min read
Working with JSON Files in R Programming
JSON stands for JavaScript Object Notation. These files contain the data in human readable format, i.e. as text. Like any other file, one can read as well as write into the JSON files. In order to work with JSON files in R, one needs to install the "rjson" package. The most common tasks done using JSON files under rjson packages are as follows: Ins
4 min read
Working with Sparse Matrices in R Programming
Sparse matrices are sparsely populated collections of elements, where there is a very less number of non-null elements. Storage of sparsely populated data in a fully dense matrix leads to increased complexities of time and space. Therefore, the data structures are optimized to store this data much more efficiently and decrease the access time of el
9 min read
Data Wrangling in R Programming - Working with Tibbles
R is a robust language used by Analysts, Data Scientists, and Business users to perform various tasks such as statistical analysis, visualizations, and developing statistical software in multiple fields.In R Programming Language Data Wrangling is a process of reimaging the raw data to a more structured format, which will help to get better insights
6 min read
Working with CSV files in R Programming
In this article, we will discuss how to work with CSV files in R Programming Language. R CSV Files R CSV Files are text files wherein the values of each row are separated by a delimiter, as in a comma or a tab. In this article, we will use the following sample CSV file. Getting and Setting the Working Directory with R CSV Files C/C++ Code # Get the
4 min read
Article Tags :
three90RightbarBannerImg