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
# create dataframe1 with college # 1 data data1= data.frame (id= c (1,2,3,4,5),
name= c ( 'sravan' , 'ojaswi' , 'bobby' ,
'gnanesh' , 'rohith' ))
# create dataframe1 with college # 2 data data2= data.frame (id= c (1,2,3,4,5,6,7),
name= c ( 'sravan' , 'ojaswi' , 'bobby' ,
'gnanesh' , 'rohith' ,
'pinkey' , 'dhanush' ))
# display data1 print (data1)
# display data2 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.
library (dplyr)
# create dataframe1 with college 1 data data1= data.frame (id= c (1,2,3,4,5),
name= c ( 'sravan' , 'ojaswi' , 'bobby' , 'gnanesh' , 'rohith' ))
# create dataframe1 with college 2 data data2= data.frame (id= c (1,2,3,4,5,6,7),
name= c ( 'sravan' , 'ojaswi' , 'bobby' , 'gnanesh' , 'rohith' ,
'pinkey' , 'dhanush' ))
# union of the two dataframes 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
library (dplyr)
# create dataframe1 with college # 1 data data1= data.frame (id= c (1,2,3,4,5),
name= c ( 'sravan' , 'ojaswi' , 'bobby' ,
'gnanesh' , 'rohith' ))
# create dataframe1 with college # 2 data data2= data.frame (id= c (1,2,3,4,5,6,7),
name= c ( 'sravan' , 'ojaswi' , 'bobby' ,
'gnanesh' , 'rohith' ,
'pinkey' , 'dhanush' ))
# union_all of the two dataframes print ( union_all (data1,data2))
|
Output: