join two dataframe and match by a common column in r

You can join two dataframes in R, and match them by a common column using the merge function. Here's an example:

# Create two dataframes
df1 <- data.frame(id = 1:5, age = c(25, 30, 35, 40, 45))
df2 <- data.frame(id = c(2, 4, 6), name = c("Alice", "Bob", "Charlie"))

# Merge the dataframes using the 'id' column as the common column
merged_df <- merge(df1, df2, by = "id", all = TRUE)

# 'all = TRUE' performs a full outer join, including rows that don't have a match in both dataframes

print(merged_df)
392 chars
11 lines

In this example, df1 and df2 are two dataframes being merged on the 'id' column. The resulting merged_df dataframe will include all rows from both dataframes based on the 'id' column.

You can adjust the all parameter to specify different types of joins such as inner join, left join, right join, or full outer join.

related categories

gistlibby LogSnag