WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

R · Intermediate · question 22 of 100

How do you merge two data frames in R? Explain the different types of joins.?

📕 Buy this interview preparation book: 100 R questions & answers — PDF + EPUB for $5

In R, merging two data frames involves combining them into a single data frame based on a shared key or column. The merge() function is used for merging data frames in R. Here’s an example of how to merge two data frames in R:

    # Create two data frames
    df1 <- data.frame(id = c(1, 2, 3), name = c("John", "Mary", "Bob"))
    df2 <- data.frame(id = c(2, 3, 4), age = c(25, 30, 35))
    
    # Merge the two data frames based on the "id" column
    merged_df <- merge(df1, df2, by = "id")

This code will create two data frames (df1 and df2) and merge them into a single data frame (merged_df) based on the shared "id" column. The resulting data frame will have columns for "id", "name", and "age".

There are several types of joins that can be used when merging data frames in R:

Inner join: An inner join returns only the rows that have matching values in both data frames. This is the default join type in merge(). For example:

    merged_df_inner <- merge(df1, df2, by = "id")

Left join: A left join returns all the rows from the first (left) data frame and matching rows from the second (right) data frame. For example:

    merged_df_left <- merge(df1, df2, by = "id", all.x = TRUE)

Right join: A right join returns all the rows from the second (right) data frame and matching rows from the first (left) data frame. For example:

    merged_df_right <- merge(df1, df2, by = "id", all.y = TRUE)

Full join: A full join returns all the rows from both data frames, and fills in missing values with NA where there are no matches. For example:

    merged_df_full <- merge(df1, df2, by = "id", all = TRUE)

It’s important to note that when merging data frames, the order of the arguments in the merge() function matters. The first argument is the left data frame, and the second argument is the right data frame. The by argument specifies the column(s) to use for the join.

In summary, merging data frames in R involves combining them into a single data frame based on a shared key or column using the merge() function. Different types of joins (inner, left, right, and full) can be used to control how the merge is performed and which rows are included in the resulting data frame.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic R interview — then scores it.
📞 Practice R — free 15 min
📕 Buy this interview preparation book: 100 R questions & answers — PDF + EPUB for $5

All 100 R questions · All topics