 Open in App
Not now

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

• Difficulty Level : Expert
• 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

 `# 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)                                       `

Output:

` 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

 `# 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)                `

Output:

```[]
 5 6 7

[]
 1 1 1

[]
 2 3 4

[]
 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
Related Articles