1

How can I update a value of a df based on another df, changing the old values that are not present in the new df? I have df1 (old) and df2 (update), and would like to produce the Desired outcome.

df1 (old)

ID iso_pres
1504a 1
1504b 1
1504c 1
1705a 1
1705b 1

df2 (update)

ID iso_pres
1504b 1
1705a 1
1705b 1

Desired outcome

ID iso_pres
1504a 0
1504b 1
1504c 0
1705a 1
1705b 1
ISalvi
  • 123
  • 4
  • Does this answer your question? [R: Updating a data frame with another data frame](https://stackoverflow.com/questions/37312659/r-updating-a-data-frame-with-another-data-frame) – Andrea M Jun 10 '22 at 14:04
  • using these command I can't update the values of the old df, just include new values – ISalvi Jun 10 '22 at 14:13

1 Answers1

1

Use %in% function to check for boolean match and replace the false with 0 in Base R.

old <- data.frame(ID = c(paste0(1504, letters[1:3]), "1705a", "1705b"), iso_press = 1)

df2 <- old[c(2,4,5),]

old$iso_press <- ifelse(old$ID %in% df2$ID, old$iso_press, 0)

or in dplyr:

old |> 
  mutate(iso_press = ifelse(ID %in% df2$ID, iso_press, 0 ))
     ID iso_press
1 1504a         0
2 1504b         1
3 1504c         0
4 1705a         1
5 1705b         1