create two dataframes and then join them by column variable in r and introduce nas when they don't match in r

main.r
# Create two dataframes
df1 <- data.frame(id = c(1, 2, 3, 4),
                  name = c("Alice", "Bob", "Charlie", "David"))

df2 <- data.frame(id = c(1, 2, 4, 5),
                  age = c(25, 30, 35, 40))

# Perform a left join on 'id' column and introduce NAs when they don't match
result <- merge(df1, df2, by = "id", all.x = TRUE)

print(result)
352 chars
12 lines

In this code snippet, two dataframes df1 and df2 are created. Then a left join is performed on the 'id' column using the merge function. The all.x = TRUE parameter specifies that all rows from df1 should be included in the result, introducing NAs where the 'id's do not match.

related categories

gistlibby LogSnag