将 R 中的两个数据帧与缺失值和重复测量合并

Merging two dataframes in R with missing values and repeated measurements

我有两个如下所示的数据框:

library(tibble)
df_1 <- tibble(id = c(1,1,1,2,2,2,3,3,3), y = c("a", "b", "c", "a", "b","c", "a", "b", "c"))
df_2 <- tibble(id = c(1,3), z = c(4,6))

我想合并两个 dfs,如下所示:

df_3 <- tibble(id = c(1,1,1,2,2,2,3,3,3), y = c("a", "b", "c", "a", "b","c", "a", "b", "c"), z = c(4,4,4,NA,NA,NA,6,6,6))

你将如何在 R 中做到这一点?谢谢!

library(dplyr)
left_join(df_1,df_2)

输出:

     id y         z
  <dbl> <chr> <dbl>
1     1 a         4
2     1 b         4
3     1 c         4
4     2 a        NA
5     2 b        NA
6     2 c        NA
7     3 a         6
8     3 b         6
9     3 c         6