How to merge data frames in R语言?

In R, you can merge data frames using the merge() function. The basic syntax of this function is as follows:

Combine datasets x and y using the variables specified in by.x and by.y. Include all observations from x and y, regardless of whether or not they have a matching value in the other dataset.

In this case, x and y are the two data frames to be merged; by is the column name or index to be merged by; by.x and by.y specify the column name or index used for merging in x and y, respectively; all.x and all.y specify whether to keep all columns that appear in x and y. By default, the merge() function will merge based on columns with the same name.

Here is an example:

Create two data frames.

df1 is a data frame that includes the columns ID with values 1, 2, and 3, and Name with corresponding values of “Tom”, “Jerry”, and “Spike”. df2 is another data frame that has the columns ID with values 2, 3, and 4, and Age with values 20, 25, and 30.

Merge data frames.

Combine data frames df1 and df2 based on the column “ID” and store the result in the merged_df.

Output the merged result.

Display the merged dataframe.

After executing the above code, you will get the merged dataframe.

ID 1 – Name Jerry – Age 20
ID 2 – Name Spike – Age 25

bannerAds