R Program to create inner, outer, left, right join(merge) from given two data frames


February 2, 2022, Learn eTutorial
1359

How to create inner, outer, left, right join(merge) from given two data frames

Here we are explaining how to write an R program to create inner, outer, left, right join(merge) from given two data frames. Here we are using a built-in function data.frame(),merge(). A data frame is used for storing data tables which has a list of vectors with equal length. The data frames are created by function data.frame(), which has tightly coupled collections of variables. And the function merge() helps to merge two data frames by common columns or row names, or database join operations. The syntax of this function is, 


merge(x, y, …) 

Where x, y are data frames, or objects to be coerced to one. And the dots(...) indicates arguments to be passed to or from methods.

How to create inner, outer, left, right join from given two data frames in the R program

Below are the steps used in the R program to create inner, outer, left, right join from the given two data frames. In this R program, we directly give the data frame to a built-in function. Here we are using variables D1, D2 for holding data frames. Call the function data.frame() for creating data frame. Finally, merge the given data frame by calling merge function differently.

ALGORITHM

STEP 1: Assign variables D1, D2 with data frames  

STEP 2: First do the left outer join as merge(D1, D2, by = "data", all.x = TRUE)

STEP 3: Next do the right outer join as merge(D1, D2, by = "data", all.y = TRUE)

STEP 4: Print the outer join as merge(D1, D2, by = "data", all = TRUE)

STEP 5: Print the cross join as merge(D1, D2, by = NULL)

R Source Code

                                          D1 = data.frame(data = c(12, 14, 10, 11))
D2 = data.frame(data= c(13, 15, 11, 12))
print("Left outer Join:")
result = merge(D1, D2, by = "data", all.x = TRUE)
print(result)
print("Right outer Join:")
result = merge(D1, D2, by = "data", all.y = TRUE)
print(result)
print("Outer Join:")
result = merge(D1, D2, by = "data", all = TRUE)
print(result)
print("Cross Join:")
result = merge(D1, D2, by = NULL)
print(result)
                                      

OUTPUT

[1] "Left outer Join:"
  data
1    10
2    11
3    12
4    14
[1] "Right outer Join:"
  data
1    11
2    12
3    13
4    15
[1] "Outer Join:"
  data
1    10
2    11
3    12
4    13
5    14
6    15
[1] "Cross Join:"
   data.x data.y
1       12      13
2       14      13
3       10      13
4       11      13
5       12      15
6       14      15
7       10      15
8       11      15
9       12      11
10      14      11
11      10      11
12      11      11
13      12      12
14      14      12
15      10      12
16      11      12