繁体   English   中英

合并 R 中具有不同行的两个数据帧

[英]Merging two data frames with different rows in R

我有两个数据框。 第一个看起来像

Country    Year  production
Germany    1996  11
France     1996  12
Greece     1996  15
UK         1996  17
USA        1996  24

第二个包含第一个数据框中的所有国家以及 2018 年的其他几个国家。看起来像这样

Country    Year   production
Germany    2018   27
France     2018   29
Greece     2018   44
UK         2018   46
USA        2018   99
Austria    2018   56
Japan      2018   66

我想合并两个数据框,最终的表格应该是这样的:

Country    Year  production
Germany    1996   11
France     1996   12
Greece     1996   15
UK         1996   17
USA        1996   24
Austria    1996   NA
Japan      1996   NA
Germany    2018   27
France     2018   29
Greece     2018   44
UK         2018   46
USA        2018   99
Austria    2018   56
Japan      2018   66

我尝试了几个函数,包括full_joinmergerbind ,但它们都不起作用。 有人有什么想法吗?

使用dplyrtidyr ,您可以使用:

bind_rows(df1, df2) %>%
 complete(Country, Year)

   Country  Year production
   <chr>   <int>      <int>
 1 Austria  1996         NA
 2 Austria  2018         56
 3 France   1996         12
 4 France   2018         29
 5 Germany  1996         11
 6 Germany  2018         27
 7 Greece   1996         15
 8 Greece   2018         44
 9 Japan    1996         NA
10 Japan    2018         66
11 UK       1996         17
12 UK       2018         46
13 USA      1996         24
14 USA      2018         99

考虑使用带有expand.gridmerge的基本 R (如果您是 package 的作者,请避免任何依赖项):

# BUILD DF OF ALL POSSIBLE COMBINATIONS OF COUNTRY AND YEAR
all_country_years <- expand.grid(Country=unique(c(df_96$Country, df_18$Country)),
                                 Year=c(1996, 2018))

# MERGE (LEFT JOIN)
final_df <- merge(all_country_years, rbind(df_96, df_18), by=c("Country", "Year"), 
                  all.x=TRUE)

# ORDER DATA AND RESET ROW NAMES
final_df <- data.frame(with(final_df, final_df[order(Year, Country),]),
                       row.names = NULL)

final_df
#    Country Year production
# 1  Germany 1996         11
# 2   France 1996         12
# 3   Greece 1996         15
# 4       UK 1996         17
# 5      USA 1996         24
# 6  Austria 1996         NA
# 7    Japan 1996         NA
# 8  Germany 2018         27
# 9   France 2018         29
# 10  Greece 2018         44
# 11      UK 2018         46
# 12     USA 2018         99
# 13 Austria 2018         56
# 14   Japan 2018         66

演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM