Union of two Objects in R Programming – union() Function
Last Updated :
19 May, 2020
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
x1 < - c( 1 , 2 , 3 , 4 , 5 , 6 , 5 , 5 )
x2 < - c( 8 , 9 )
x3 < - union(x1, x2)
print (x3)
|
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
data_x < - data.frame(x1 = c( 5 , 6 , 7 ),
x2 = c( 1 , 1 , 1 ))
data_y < - data.frame(y1 = c( 2 , 3 , 4 ),
y2 = c( 2 , 2 , 2 ))
data_z < - union(data_x, data_y)
print (data_z)
|
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.
Share your thoughts in the comments
Please Login to comment...