Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overwrite a specific value in a dataframe, based on matching values

Tags:

r

dplyr

tidyverse

My data is in a format like this:

#>   country year value
#> 1     AUS 2019   100
#> 2     USA 2019   120
#> 3     AUS 2018    90
df <- data.frame(stringsAsFactors=FALSE,
     country = c("AUS", "USA", "AUS"),
        year = c(2019, 2019, 2018),
       value = c(100, 120, 90)
)

and I have an one row dataframe that represents a revision that should overwrite the existing record in my data.

#>   country year value
#> 1     AUS 2019   500
df2 <- data.frame(stringsAsFactors=FALSE,
                  country = c("AUS"),
                     year = c(2018),
                    value = c(500)
             )

My desired output is:

#>   country year value
#> 1     AUS 2019   100
#> 2     USA 2019   120
#> 3     AUS 2018   500

I know how to find the row to overwrite:

library(tidyverse)
df %>% filter(country == overwrite$country & year == overwrite$year) %>% 
  mutate(value = overwrite$value)

but how do I put that back in the original dataframe?

Tidyverse answers are easier for me to work with, but I'm open to any solutions.

like image 263
Jeremy K. Avatar asked Jul 09 '26 02:07

Jeremy K.


1 Answers

Using mutate and if_else:

library(tidyverse)

df %>% 
mutate(value = if_else(country %in% df2$country & year %in% df2$year, df2$value, value))

Results in:

country year value
1     AUS 2019   100
2     USA 2019   120
3     AUS 2018   500

like image 75
Matt Avatar answered Jul 10 '26 16:07

Matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!