Reputation: 123
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 |
Upvotes: 1
Views: 305
Reputation:
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
Upvotes: 1