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
R
data1= data.frame (id= c (1,2,3,4,5),
name= c ( 'sravan' , 'ojaswi' , 'bobby' ,
'gnanesh' , 'rohith' ))
data2= data.frame (id= c (1,2,3,4,5,6,7),
name= c ( 'sravan' , 'ojaswi' , 'bobby' ,
'gnanesh' , 'rohith' ,
'pinkey' , 'dhanush' ))
print (data1)
print (data2)
|
Output:
For both of these functions to work successfully, dplyr package should be installed and imported to the working space.
union() function
union() is used to return all the elements when two data frames are combined. It doesn’t repeat duplicate values.
Syntax:
union(dataframe1,dataframe2)
Example: R program to perform union among two dataframes.
R
library (dplyr)
data1= data.frame (id= c (1,2,3,4,5),
name= c ( 'sravan' , 'ojaswi' , 'bobby' , 'gnanesh' , 'rohith' ))
data2= data.frame (id= c (1,2,3,4,5,6,7),
name= c ( 'sravan' , 'ojaswi' , 'bobby' , 'gnanesh' , 'rohith' ,
'pinkey' , 'dhanush' ))
print ( union (data1,data2))
|
Output:
union_all() function
This will return all the data from both dataframes. Unlike union, it will return duplicate data also.
Syntax:
union_all(dataframe1,dataframe2)
Example: R program to perform union_all operation
R
library (dplyr)
data1= data.frame (id= c (1,2,3,4,5),
name= c ( 'sravan' , 'ojaswi' , 'bobby' ,
'gnanesh' , 'rohith' ))
data2= data.frame (id= c (1,2,3,4,5,6,7),
name= c ( 'sravan' , 'ojaswi' , 'bobby' ,
'gnanesh' , 'rohith' ,
'pinkey' , 'dhanush' ))
print ( union_all (data1,data2))
|
Output:
Last Updated :
21 Jul, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...