我有两个df,我需要将它们合并。
df1看起来像这样:
COUNTRY YEAR TRADE
Spain 2016 276
Germany 2016 323
France 2016 392
Spain 2017 456
Germany 2017 564
France 2017 359
df2看起来像这样:
COUNTRY GDP2016 GDP2017
Spain 1111 999
Germany 2222 888
France 3333 777
通过简单的df3 <- merge(df1,df2, by = "COUNTRY")
我会得到:
COUNTRY YEAR TRADE GDP2016 GDP2017
Spain 2016 276 1111 999
Germany 2016 323 2222 888
France 2016 392 3333 777
Spain 2017 456 1111 999
Germany 2017 564 2222 888
France 2017 359 3333 777
但是我想要得到的是:
COUNTRY YEAR TRADE GDP
Spain 2016 276 1111
Germany 2016 323 2222
France 2016 392 3333
Spain 2017 456 999
Germany 2017 564 888
France 2017 359 777
可能我必须使用某种条件,但我不知道如何。我将不胜感激。
答案 0 :(得分:0)
使用ifelse()
函数并从dplyr
进行突变:
library(dplyr)
df3 <- merge(df1,df2, by = "COUNTRY")
df3 <- df3 %>% mutate(GDP = ifelse(YEAR == 2016, GDP2016, GDP2017))
df3 <- subset(df3, select = -c(GDP2016, GDP2017))
输出:
> df3
COUNTRY YEAR TRADE GDP
1 France 2016 392 3333
2 France 2017 359 777
3 Germany 2016 323 2222
4 Germany 2017 564 888
5 Spain 2016 276 1111
6 Spain 2017 456 999