Union of two Objects in R Programming – union() Function

union() function in R Language is used to combine the data of two objects. This function takes two objects like Vectors, dataframes, etc. as arguments and results in a third object with the combination of the data of both the objects.

Syntax: union(x, y)

Parameters:
x and y: Objects with sequence of items

Example 1: Union of two Vectors

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to illustrate
# union of two vectors
  
# Vector 1
x1 <- c(1, 2, 3, 4, 5, 6, 5, 5)   
  
# Vector 2 
x2 <- c(8, 9)    
  
# Union of two vectors  
x3 <- union(x1, x2)      
  
print(x3)                                      

chevron_right


Output:



[1] 1 2 3 4 5 6 8 9

Here in the above code, the vector x1 contains values from 1-6, and x2 has two values. Now the union of these two vector x1 and x2 will combine each of the values present in them just once.

Note: Union of two vectors removes the duplicate elements in the final vector.

Example 2: Union of two dataframes

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to illustrate 
# the union of two data frames
  
# Data frame 1
data_x <- data.frame(x1 = c(5, 6, 7),    
                     x2 = c(1, 1, 1))
  
# Data frame 2
data_y <- data.frame(y1 = c(2, 3, 4),       
                     y2 = c(2, 2, 2))
  
# R union two data frames
data_z <- union(data_x, data_y)  
  
print(data_z)               

chevron_right


Output:

[[1]]
[1] 5 6 7

[[2]]
[1] 1 1 1

[[3]]
[1] 2 3 4

[[4]]
[1] 2 2 2

Here in the above code, we have created two data frames first with x1, x2 and second have y1, y2. Union of these two data frames creates a third data frame with combined values.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.