The merge function in the r language can achieve a similar effect of left join right join or union similar to SQL.
DF1 = data. frame (customerid = C (1:6), product = C (REP ("toaster", 3), Rep ("radio", 3)> df2 = data. frame (customerid = C (2, 4, 6, 7), State = C (REP ("Alabama", 3), Rep ("Ohio", 1 )))
> DF1
Customerid Product
1 toaster
2 2 toaster
3 3 toaster
4 4 radio
5 5 Radio
6 6 Radio
> Df2
Customerid state
1 2 Alabama
2 4 Alabama
3 6 Alabama
4 7 Ohio
> Merge (DF1, df2, all = true)
Customerid product state
1 1 toaster <Na>
2 2 toaster Alabama
3 3 toaster <Na>
4 4 radio Alabama
5 5 Radio <Na>
6 6 Radio Alabama
7 <Na> Ohio
# Full join Effect> Merge (DF1, df2, all. x = true)
Customerid product state
1 1 toaster <Na>
2 2 toaster Alabama
3 3 toaster <Na>
4 4 radio Alabama
5 5 Radio <Na>
6 6 Radio Alabama
# Effect of left join
> Merge (DF1, df2, all. Y = true)
Customerid product state
1 2 toaster Alabama
2 4 radio Alabama
3 6 Radio Alabama
4 7 <Na> Ohio
# Right join effect ..
Under the same column name of DF1 and df2
> DF1 <-Data. Frame (col1 = C (1, 2), col2 = C (2, 3 ))
> Df2 <-Data. Frame (col1 = C (2,100), col2 = C ))
> Merge (DF1, df2, all = true)
Col1 col2
1 1 2
2 2 3
3 4 100
# This achieves the Union effect.
Run
mergeWhen a function is used, the function automatically finds the columns in the DF1 and df2 data boxes, that is, the column ID (that is, equivalent
by= "id") When the Parameter
all= FALSEThe rows with the same column values in the two data boxes are output, similar to the intersection of the column IDs in the two data boxes ). In this example, the ID is 2 or 7. In addition, we can find that the input sequence of DF1 and df2 does not affect the final result, but only the sequence of the heights and weights columns in the output result. For more details, refer to the use of the http://rstudio-pubs-static.s3.amazonaws.com/13602_96265a9b3bac4cb1b214340770aa18a1.html ------------ by parameter
In the preceding example, The by parameter has only one value. If there are two values (that is, the vector with a length of 2), that is, the two data boxes have two common columns.
df1$sex <- c("f", "m", "f", "f", "m")df2$sex <- c("f", "f", "m", "m", "f", "f", "f")merge(df1, df2)
## id sex heights weights## 1 2 f 62 113## 2 7 m 67 135
merge(df1, df2, by = c("id", "sex"))
## id sex heights weights## 1 2 f 62 113## 2 7 m 67 135
merge(df1, df2, by = "id")
## id heights sex.x weights sex.y## 1 2 62 f 113 f## 2 7 67 m 135 m
After adding one column for the two data boxes, they have two common columns. When runningmergeThe function then finds that the function will automatically find the common column, and then find the value of the ID and sex columns. In addition, if you only setby= "id"The sex column in the two data boxes is output in the form of sex. X and sex. Y.
Case study of merge functions in R Language