The Wayback Machine - https://web.archive.org/web/20241122174951/https://www.geeksforgeeks.org/dplyr-package-in-r-programming/
Open In App

dplyr Package in R Programming

Last Updated : 20 Dec, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will discuss Aggregating and analyzing data with dplyr package in the R Programming Language.

dplyr Package in R

The dplyr package in R Programming Language is a structure of data manipulation that provides a uniform set of verbs, helping to resolve the most frequent data manipulation hurdles.

  • By limiting the choices the focus can now be more on data manipulation difficulties.
  • There are uncomplicated “verbs”, functions present for tackling every common data manipulation and the thoughts can be translated into code faster.
  • There are valuable backends and hence waiting time for the computer is reduced.

Here are some key functions and concepts within the dplyr package in R.

Data Frame and Tibble

Data frames in dplyr in R is organized tables where each column stores specific types of information, like names, ages, or scores.for creating a data frame involves specifying column names and their respective values.

R




df <- data.frame(
  Name = c("vipul", "jayesh", "anurag"),
  Age = c(25, 23, 22),
  Score = c(95, 89, 78)
)
df


Output:

    Name Age Score
1 vipul 25 95
2 jayesh 23 89
3 anurag 22 78

On the other hand, tibbles, introduced through the tibble package, share similar functionality but offer enhanced user-friendly features. The syntax for creating a tibble is comparable to that of a data frame.

Pipes (%>%)

dplyr in R The pipe operator (%>%) in dplyr package, which allows us to chain multiple operations together, improving code readability.

R




# Load necessary libraries
library(dplyr)
 
# Example: Chain operations using the pipe operator
result <- mtcars %>%
  filter(mpg > 20) %>%        # Filter rows where mpg is greater than 20
  select(mpg, cyl, hp) %>%    # Select specific columns
  group_by(cyl) %>%           # Group the data by the 'cyl' variable
  summarise(mean_hp = mean(hp))  # Calculate the mean horsepower for each group
 
# Display the result
print(result)


Output:

    cyl mean_hp
<dbl> <dbl>
1 4 82.6
2 6 110

Verb Functions

dplyr in R provides various important functions that can be used for Data Manipulation. These are: 

filter() Function

For choosing cases and using their values as a base for doing so.

R




# Create a data frame with missing data
d <- data.frame(name = c("Abhi", "Bhavesh", "Chaman", "Dimri"),
                age = c(7, 5, 9, 16),
                ht = c(46, NA, NA, 69),
                school = c("yes", "yes", "no", "no"))
 
# Display the data frame
print(d)
 
# Finding rows with NA value
rows_with_na <- d %>% filter(is.na(ht))
print(rows_with_na)
 
# Finding rows with no NA value
rows_without_na <- d %>% filter(!is.na(ht))
print(rows_without_na)


Output: 

     name age ht school
1 Abhi 7 46 yes
2 Bhavesh 5 NA yes
3 Chaman 9 NA no
4 Dimri 16 69 no
Finding rows with NA value
name age ht school
1 Bhavesh 5 NA yes
2 Chaman 9 NA no
Finding rows with no NA value
name age ht school
1 Abhi 7 46 yes
2 Dimri 16 69 no

arrange():

For reordering of the cases.

R




# Create a data frame with missing data
d <- data.frame( name = c("Abhi", "Bhavesh", "Chaman", "Dimri"),
                 age = c(7, 5, 9, 16),
                 ht = c(46, NA, NA, 69),
                 school = c("yes", "yes", "no", "no") )
d
 
# Arranging name according to the age
d.name<- arrange(d, age)
print(d.name)


Output: 

     name age ht school
1 Abhi 7 46 yes
2 Bhavesh 5 NA yes
3 Chaman 9 NA no
4 Dimri 16 69 no

Arranging name according to the age
name age ht school
1 Bhavesh 5 NA yes
2 Abhi 7 46 yes
3 Chaman 9 NA no
4 Dimri 16 69 no

select() and rename():

For choosing variables and using their names as a base for doing so.

R




# Create a data frame with missing data
d <- data.frame(name=c("Abhi", "Bhavesh",
                        "Chaman", "Dimri"),
                 age=c(7, 5, 9, 16),
                 ht=c(46, NA, NA, 69),
                 school=c("yes", "yes", "no", "no"))
 
# startswith() function to print only ht data
select(d, starts_with("ht"))
 
# -startswith() function to print
# everything except ht data
select(d, -starts_with("ht"))
 
# Printing column 1 to 2
select(d, 1: 2)
 
# Printing data of column
# heading containing 'a'
select(d, contains("a"))
 
# Printing data of column
# heading which matches 'na'
select(d, matches("na"))


Output: 


ht
1 46
2 NA
3 NA
4 69
everything except ht data
name age school
1 Abhi 7 yes
2 Bhavesh 5 yes
3 Chaman 9 no
4 Dimri 16 no
Printing column 1 to 2
name age
1 Abhi 7
2 Bhavesh 5
3 Chaman 9
4 Dimri 16
heading containing 'a'
name age
1 Abhi 7
2 Bhavesh 5
3 Chaman 9
4 Dimri 16
heading which matches 'na'
name
1 Abhi
2 Bhavesh
3 Chaman
4 Dimri

mutate() and transmute():

Addition of new variables which are the functions of prevailing variables.

R




# Create a data frame with missing data
d <- data.frame( name = c("Abhi", "Bhavesh",
                          "Chaman", "Dimri"),
                 age = c(7, 5, 9, 16),
                 ht = c(46, NA, NA, 69),
                 school = c("yes", "yes", "no", "no") )
 
# Calculating a variable x3 which is sum of height
# and age printing with ht and age
mutate(d, x3 = ht + age)
 
# Calculating a variable x3 which is sum of height
# and age printing without ht and age
transmute(d, x3 = ht + age)


Output: 

     name age ht school
1 Abhi 7 46 yes
2 Bhavesh 5 NA yes
3 Chaman 9 NA no
4 Dimri 16 69 no
Calculating a variable x3 which is sum of height

name age ht school x3
1 Abhi 7 46 yes 53
2 Bhavesh 5 NA yes NA
3 Chaman 9 NA no NA
4 Dimri 16 69 no 85
Calculating a variable x3 which is sum of height
x3
1 53
2 NA
3 NA
4 85

summarise():

Condensing various values to one value.

R




# Create a data frame with missing data
d <- data.frame( name = c("Abhi", "Bhavesh",
                          "Chaman", "Dimri"),
                 age = c(7, 5, 9, 16),
                 ht = c(46, NA, NA, 69),
                 school = c("yes", "yes", "no", "no") )
 
# Calculating mean of age
summarise(d, mean = mean(age))
 
# Calculating min of age
summarise(d, med = min(age))
 
# Calculating max of age
summarise(d, med = max(age))
 
# Calculating median of age
summarise(d, med = median(age))


Output: 

Calculating mean of age
mean
1 9.25
Calculating minimum age
med
1 5
Calculating max of age
med
1 16
Calculating median of age
med
1 8

sample_n() and sample_frac():

For taking random specimens.

R




# Create a data frame with missing data
d <- data.frame( name = c("Abhi", "Bhavesh",
                          "Chaman", "Dimri"),
                 age = c(7, 5, 9, 16),
                 ht = c(46, NA, NA, 69),
                 school = c("yes", "yes", "no", "no") )
 
# Printing three rows
sample_n(d, 3)
 
# Printing 50 % of the rows
sample_frac(d, 0.50)


Output: 

    name age ht school
1 Chaman 9 NA no
2 Dimri 16 69 no
3 Abhi 7 46 yes
Printing 50 % of the rows
name age ht school
1 Abhi 7 46 yes
2 Dimri 16 69 no


Previous Article
Next Article

Similar Reads

Rank variable by group using Dplyr package in R
In this article, we are going to see how to rank the variable by group using dplyr in R Programming Language. The dplyr package in R is used to perform mutations and data manipulations in R. It is particularly useful for working with data frames and data tables. The package can be downloaded and installed into the working directory using the follow
2 min read
Union() & union_all() functions in Dplyr package in R
In this article, we will discuss union() and union_all() functions using Dplyr package in the R programming language. Dataframes in use: Example: R program to create data frames with college student data and display them C/C++ Code # create dataframe1 with college # 1 data data1=data.frame(id=c(1,2,3,4,5), name=c('sravan','ojaswi','bobby', 'gnanesh
2 min read
How to Remove a Column using Dplyr package in R
In this article, we are going to remove a column(s) in the R programming language using dplyr library. Dataset in use: Remove column using column nameHere we will use select() method to select and remove column by its name. Syntax: select(dataframe,-column_name) Here, dataframe is the input dataframe and column_name is the column in the dataframe t
3 min read
How to Remove a Column by name and index using Dplyr Package in R
In this article, we are going to remove columns by name and index in the R programming language using dplyr package. Dataset in use: Remove a column by using column name We can remove a column with select() method by its column name. Syntax: select(dataframe,-column_name) Where, dataframe is the input dataframe and column_name is the name of the co
2 min read
Drop multiple columns using Dplyr package in R
In this article, we will discuss how to drop multiple columns using dplyr package in R programming language. Dataset in use: Drop multiple columns by using the column name We can remove a column with select() method by its column name Syntax: select(dataframe,-c(column_name1,column_name2,.,column_name n) Where, dataframe is the input dataframe and
4 min read
Sum Across Multiple Rows and Columns Using dplyr Package in R
In this article, we are going to see how to sum multiple Rows and columns using Dplyr Package in R Programming language. The dplyr package is used to perform simulations in the data by performing manipulations and transformations. It can be installed into the working space using the following command : install.packages("dplyr")Calculating row sums
3 min read
Create a ranking variable with Dplyr package in R
In this article, we will discuss how to create a ranking variable with the Dplyr package in R. Installation To install this package type the below command in the terminal. install.packages("dplyr") The mutate method can be used to rearrange data into a different orientation by performing various aggregate and statistic method and assigning it to ne
3 min read
Create, modify, and delete columns using dplyr package in R
In this article, we will discuss mutate function present in dplyr package in R Programming Language to create, modify, and delete columns of a dataframe. Create new columns Columns can be inserted either by appending a new column or using existing columns to evaluate a new column. By default, columns are added to the far right. Although columns can
3 min read
Joining Data in R with Dplyr Package
In this article, we will be looking at the different methods of joining data with the dplyr in the R programming language. We need to load the dplyr package. Type the below commands - Install - install.packages("dplyr") Load - library("dplyr") Method 1: Using inner join In this method of joining data, the user call the inner_join function, which wi
5 min read
Case when statement in R Dplyr Package using case_when() Function
This article focuses upon the case when statement in the R programming language using the case_when() function from the Dplyr package. Case when is a mechanism using which we can vectorize a bunch of if and else if statements. In simple words, using a case when statement we evaluate a condition expression, and based on that we make decisions. For e
4 min read
cumall(), cumany() & cummean() R Functions of dplyr Package
In this article, we will discuss about cumall(), cummany(), and cummean() functions in R Programming Language. Which are available in dplyr() package. We have to install and load dplyr package. Install - install.packages("dplyr") Load - library("dplyr")cumall() This function will check whether the first element is TRUE. if yes, then it will return
3 min read
Data Manipulation in R with Dplyr Package
In this article let's discuss manipulating data in the R programming language. In order to manipulate the data, R provides a library called dplyr which consists of many built-in methods to manipulate the data. So to use the data manipulation function, first need to import the dplyr package using library(dplyr) line of code. Below is the list of a f
5 min read
Remove Rows with NA Using dplyr Package in R
NA means Not Available is often used for missing values in a dataset. In Machine Learning NA values are a common problem and if not treated properly can create severe issues during data analysis. NA is also referred as NaN which means Not a number. To understand NA values we can think of an admission form with different columns including Blood Grou
5 min read
What is the difference between ensym and enquo when programming with dplyr?
When programming with dplyr, a popular R package for data manipulation, you'll often encounter functions like ensym() and enquo() as part of tidy evaluation. Both of these functions are used to capture expressions passed into functions, but they serve slightly different purposes and behave differently under certain circumstances. Understanding the
4 min read
Group by one or more variables using Dplyr in R
The group_by() method is used to divide and segregate date based on groups contained within the specific columns. The required column to group by is specified as an argument of this function. It may contain multiple column names. Syntax: group_by(col1, col2, ...) Example 1: Group by one variable C/C++ Code # installing required libraries library(
2 min read
Single-Table Analysis with dplyr using R Language
The dplyr package is used to perform simulations in the data by performing manipulations and transformations. It can be installed into the working space using the following command : install.packages("dplyr") Let's create the main dataframe: C/C++ Code #installing the required libraries library(dplyr) #creating a data frame data_frame = data.frame(
5 min read
How to Create Frequency Table by Group using Dplyr in R
In this article, we will be looking at the approach to creating a frequency table group with its working examples in the R programming language. Create Frequency Table by Group using dplyr package: In this approach to create the frequency table by group, the user first needs to import and install the dplyr package in the working console, and then t
2 min read
Reorder the column of dataframe in R using Dplyr
In this article, we will discuss how to rearrange or reorder the column of the dataframe using dplyr package in R Programming Language. Creating Dataframe for demonstration: C/C++ Code # load the package library(dplyr) # create the dataframe with three columns # id , department and salary with 8 rows data = data.frame(id = c(7058, 7059, 7060, 7089,
4 min read
Select Random Samples in R using Dplyr
In this article, we will be looking at different methods for selecting random samples from the Dplyr package of the R programming language. To install and import the Dplyr package in the R programming language, the user needs to follow the syntax: Syntax: install.packages("dplyr") library(dplyr) Method 1: Using Sample_n() function Sample_n() functi
2 min read
Group by function in R using Dplyr
Group_by() function belongs to the dplyr package in the R programming language, which groups the data frames. Group_by() function alone will not give any output. It should be followed by summarise() function with an appropriate action to perform. It works similar to GROUP BY in SQL and pivot table in excel. Syntax: group_by(col,...) Syntax: group_b
2 min read
Dplyr - Groupby on multiple columns using variable names in R
The group_by() method is used to group the data contained in the data frame based on the columns specified as arguments to the function call. The group_by() function takes as an argument, the across and all of the methods which has to be applied on the specified grouping over all the columns of the data frame. Syntax: group_by(col1, col2,..) This i
2 min read
Intersection of dataframes using Dplyr in R
In this article, we will discuss how to find the Intersection of two dataframes using the Dplyr package in R programming language. Dplyr provides intersect() method to get the common data in two dataframes. Syntax: intersect(dataframe1,dataframe2,dataframe3,........,dataframe n) We can perform this operation on the two dataframes. Example 1: R prog
1 min read
Get difference of dataframes using Dplyr in R
In this article, we will discuss How to find the difference between two dataframes using the Dplyr package in the R programming language. Set difference refers to getting or extracting those values from one dataset that are not present in the other. For this, dplyr supports a function called setdiff(). setdiff() is used to return the data present i
1 min read
Select variables (columns) in R using Dplyr
In this article, we are going to select variables or columns in R programming language using dplyr library. Dataset in use: Select column with column name Here we will use select() method to select column by its name Syntax: select(dataframe,column1,column2,.,column n) Here, data frame is the input dataframe and columns are the columns in the dataf
5 min read
Remove Duplicate rows in R using Dplyr
In this article, we are going to remove duplicate rows in R programming language using Dplyr package. Method 1: distinct() This function is used to remove the duplicate rows in the dataframe and get the unique data Syntax: distinct(dataframe) We can also remove duplicate rows based on the multiple columns/variables in the dataframe Syntax: distinct
3 min read
Rename the column name in R using Dplyr
In this article, we are going to rename the column name using dplyr package in the R programming language. Dataset in use: Method 1: Using rename() This method is used to rename the columns in the dataframe Syntax: rename(dataframe,new_columnname=old_column,.............,name,new_columnname=old_columnname) Where dataframe is the input dataframe, ne
3 min read
Filter data by multiple conditions in R using Dplyr
In this article, we will learn how can we filter dataframe by multiple conditions in R programming language using dplyr package. The filter() function is used to produce a subset of the data frame, retaining all rows that satisfy the specified conditions. The filter() method in R programming language can be applied to both grouped and ungrouped dat
3 min read
Sorting DataFrame in R using Dplyr
In this article, we will discuss about how to sort a dataframe in R programming language using Dplyr package. The package Dplyr in R programming language provides a function called arrange() function which is useful for sorting the dataframe. Syntax : arrange(.data, ...) The methods given below show how this function can be used in various ways to
3 min read
Filter multiple values on a string column in R using Dplyr
In this article we will learn how to filter multiple values on a string column in R programming language using dplyr package. Method 1: Using filter() method filter() function is used to choose cases and filtering out the values based on the filtering conditions. Syntax: filter(df, condition) Parameters: df: Dataframe object condition: filtering ba
3 min read
Filter or subsetting rows in R using Dplyr
In this article, we are going to filter the rows from dataframe in R programming language using Dplyr package. Dataframe in use: Method 1: Subset or filter a row using filter() To filter or subset row we are going to use the filter() function. Syntax: filter(dataframe,condition) Here, dataframe is the input dataframe, and condition is used to filte
6 min read
Article Tags :
three90RightbarBannerImg