如何使用 dplyr 连接多个数据框
通常,您可能对在 R 中连接多个数据帧感兴趣。幸运的是,使用dplyr包中的left_join()函数可以轻松做到这一点。
library(dplyr)
例如,假设我们有以下三个数据框:
#create data frame
df1 <- data.frame(a = c('a', 'b', 'c', 'd', 'e', 'f'),
b = c(12, 14, 14, 18, 22, 23))
df2 <- data.frame(a = c('a', 'a', 'a', 'b', 'b', 'b'),
c = c(23, 24, 33, 34, 37, 41))
df3 <- data.frame(a = c('d', 'e', 'f', 'g', 'h', 'i'),
d = c(23, 24, 33, 34, 37, 41))
要将三个数据帧连接在一起,我们可以简单地执行两个左连接,一个接一个:
#join the three data frames df1 %>% left_join (df2, by='a') %>% left_join (df3, by='a') abcd 1 to 12 23 NA 2 to 12 24 NA 3 to 12 33 NA 4 b 14 34 NA 5 b 14 37 NA 6 b 14 41 NA 7 c 14 NA NA 8 d 18 NA 23 9th 22 NA 24 10 f 23 NA 33
请注意,您还可以将此连接的结果保存为数据框:
#join the three data frames and save result as new data frame named all_data all_data <- df1 %>% left_join (df2, by='a') %>% left_join (df3, by='a') #view summary of resulting data frame glimpse(all_data) Comments: 10 Variables: 4 $ a <chr> "a", "a", "a", "b", "b", "b", "c", "d", "e", "f" $b<dbl> 12, 12, 12, 14, 14, 14, 14, 18, 22, 23 $ c <dbl> 23, 24, 33, 34, 37, 41, NA, NA, NA, NA $ d <dbl> NA, NA, NA, NA, NA, NA, NA, 23, 24, 33