0

I have the following two dataframes. The first is the main dataframe with a lot of observations, the second contains updated values for one country. Two example dataframes are displayed below:

df1 <- data.frame(country = c("A","A","B","B") , value = 1:4, date = as.Date(c("01-01-2000","01-02-2000","01-01-2000","01-02-2000"),"%d-%m-%Y"))

df2 <- data.frame(country = c("A","A","A","A") , value = c(1,2,7,8), date = as.Date(c("01-01-2000","01-02-2000","01-03-2000","01-04-2000"),"%d-%m-%Y"))

Now, I would like to use the second dataframe to update the values in df1. The results should look like:

df1
    country value   date
1   A       1   2000-01-01
2   A       2   2000-02-01
3   A       7   2000-03-01
4   A       8   2000-04-01
5   B       3   2000-01-01
6   B       4   2000-02-01

I am quite new to R, so I would appreciate any help! What is the most efficient way in doing this? I already tried some ways but could not figure out a fast and neat way to do it. Thanks a lot!

elio rico
  • 71
  • 1
  • 10

1 Answers1

2

I believe this is what you are looking for:

library(dplyr)

df1 %>%
  full_join(df2) %>%
  arrange(country)

#    country value    date
# 1       A     1 2000-01-01
# 2       A     2 2000-02-01
# 3       A     7 2000-03-01
# 4       A     8 2000-04-01
# 5       B     3 2000-01-01
# 6       B     4 2000-02-01

or

merge(df1, df2, all.x = TRUE, all.y = TRUE)
AlexB
  • 3,061
  • 2
  • 17
  • 19