The Wayback Machine - https://web.archive.org/web/20240828110753/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
News Follow

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
Which Working Profiles Required R Programming Language?
R programming language is essential in various professional profiles that involve statistical analysis, data visualization, data manipulation, and report generation. Key roles that require proficiency in R include data scientists, statisticians, economists, biostatisticians, and data analysts, particularly in sectors like healthcare, finance, acade
3 min read
What is the Relation Between R Programming and Hadoop Programming?
The relation between R programming and Hadoop revolves around integrating R with the Hadoop ecosystem to analyze large datasets that are stored in a Hadoop environment. R, primarily used for statistical analysis and data visualization, is not inherently built for handling big data. However, when combined with Hadoop, it can leverage Hadoop's distri
3 min read
Get and Set Working Directory in R
In this article, we are going to see how to get and set a working directory in R Programming Language. How to Get Working directory: getwd(): The getwd() method is used to gather information about the current working pathname or default working directory. This function has no arguments. It returns an absolute pathname. It returns NULL in case there
2 min read
Working With Different Versions of an R Package
R programming language offers different functionalities through different packages available in online repositories. The official repository CRAN keeps updating these packages and frequently publishes newer versions of packages. R's package system is set by default to overwrite the existing versions of packages so that the user always has the lates
8 min read
Working with Legends in R using ggplot2
A legend in a plot helps us to understand which groups belong to each bar, line, or box based on its type, color, etc. We can add a legend box in R using the legend() function. These work as guides. The keys can be determined by scale breaks. In this article, we will be working with legends and associated customization using ggplot2 in R programmin
7 min read
How to Fix in R: Cannot change working directory
In this article, we focus on how we can fix the "cannot change working directory" error in the R programming language. One error that one may encounter in R is: Error in setwd("C:/Bhuwanesh/gfg") : cannot change working directory Such an error occurs when we try to set a working directory in R, but a part of the file path is misspelled. When this e
2 min read
Working with Text in R
R Programming Language is used for statistical computing and is used by many data miners and statisticians for developing statistical software and data analysis. It includes machine learning algorithms, linear regression, time series, and statistical inference to name a few. R and its libraries implement a wide variety of statistical and graphical
6 min read
Working with Axes in R using ggplot2
The ggplot2 package is a powerful and widely used package for graphic visualization. It can be used to provide a lot of aesthetic mappings to the plotted graphs. This package is widely available in the R Programming Language. The package can be downloaded and installed into the working space using the following command. install.packages("ggplot2")T
7 min read
Working with R Scripts in Power BI Desktop
Power BI is a very useful tool when it comes to working with powerful scripting languages such as R Programming. Power BI in itself is a powerful tool for data visualization. Using R scripts in Power BI Desktop can further enhance your data analysis and visualization capabilities, making the job of data analysts much easier. Working with R Scripts
4 min read
Why Would you Learn R if you have Excel working well?
Answer: While Excel is a powerful tool for basic data analysis and visualization, learning R offers significant advantages for more complex, large-scale, and advanced statistical tasks. R is particularly valuable for handling larger datasets, automating repetitive tasks, performing sophisticated statistical analyses, and creating advanced data visu
3 min read
Getting the Modulus of the Determinant of a Matrix in R Programming - determinant() Function
determinant() function in R Language is a generic function that returns separately the modulus of the determinant, optionally on the logarithm scale, and the sign of the determinant. Syntax: determinant(x, logarithm = TRUE, ...) Parameters: x: matrix logarithm: if TRUE (default) return the logarithm of the modulus of the determinant Example 1: # R
2 min read
tidyr Package in R Programming
Packages in the R language are a collection of R functions, compiled code, and sample data. They are stored under a directory called “library” in the R environment. By default, R installs a set of packages during installation. One of the most important packages in R is the tidyr package. The sole purpose of the tidyr package is to simplify the proc
14 min read
Get Exclusive Elements between Two Objects in R Programming - setdiff() Function
setdiff() function in R Programming Language is used to find the elements which are in the first Object but not in the second Object. Syntax: setdiff(x, y) Parameters: x and y: Objects with sequence of itemsR - setdiff() Function ExampleExample 1: Apply setdiff to Numeric Vectors in R Language C/C++ Code # R program to illustrate # the use of setdi
2 min read
Add Leading Zeros to the Elements of a Vector in R Programming - Using paste0() and sprintf() Function
paste0() and sprintf() functions in R Language can also be used to add leading zeros to each element of a vector passed to it as argument. Syntax: paste0("0", vec) or sprintf("%0d", vec)Parameters: paste0: It will add zeros to vector sprintf: To format a vector(adding zeros) vec: Original vector dataReturns: Vectors by addition of leading zeros Exa
1 min read
Clustering in R Programming
Clustering in R Programming Language is an unsupervised learning technique in which the data set is partitioned into several groups called clusters based on their similarity. Several clusters of data are produced after the segmentation of data. All the objects in a cluster share common characteristics. During data mining and analysis, clustering is
6 min read
Compute Variance and Standard Deviation of a value in R Programming - var() and sd() Function
var() function in R Language computes the sample variance of a vector. It is the measure of how much value is away from the mean value. Syntax: var(x) Parameters: x : numeric vector Example 1: Computing variance of a vector # R program to illustrate # variance of vector # Create example vector x &lt;- c(1, 2, 3, 4, 5, 6, 7) # Apply var function in
1 min read
Compute Density of the Distribution Function in R Programming - dunif() Function
dunif() function in R Language is used to provide the density of the distribution function. Syntax: dunif(x, min = 0, max = 1, log = FALSE) Parameters: x: represents vector min, max: represents lower and upper limits of the distribution log: represents logical value for probabilities Example 1: # Create vector of random deviation u &lt;- runif(20)
1 min read
Compute Randomly Drawn F Density in R Programming - rf() Function
rf() function in R Language is used to compute random density for F Distribution. Syntax: rf(N, df1, df2) Parameters: N: Sample Size df: Degree of Freedom Example 1: # R Program to compute random values # of F Density # Setting seed for # random number generation set.seed(1000) # Set sample size N &lt;- 20 # Calling rf() Function y &lt;- rf(N, df1
1 min read
Data Handling in R Programming
R Programming Language is used for statistics and data analytics purposes. Importing and exporting of data is often used in all these applications of R programming. R language has the ability to read different types of files such as comma-separated values (CSV) files, text files, excel sheets and files, SPSS files, SAS files, etc. R allows its user
5 min read
Return a Matrix with Lower Triangle as TRUE values in R Programming - lower.tri() Function
lower.tri() function in R Language is used to return a matrix of logical values with lower triangle as TRUE. Syntax: lower.tri(x, diag) Parameters: x: Matrix object diag: Boolean value to include diagonal Example 1: # R program to print the # lower triangle of a matrix # Creating a matrix mat &lt;- matrix(c(1:9), 3, 3, byrow = T) # Calling lower.tr
1 min read
Article Tags :