Reputation: 145
I have a dataframe (Df1) that needs to be updated with a 2nd dataframe (Df2).
If the "Bird.ID" is found in Df2, then the column "Status" takes the "Alive" status in Df1 (by matching IDs)
Df1$Status[match(Df2$Bird.ID, Df1$ID)] <- "Alive"
The problem is that in Df1, the "Status" column can have "Dead" value (and a dead bird should remain dead).
I want to find a way to fix the "dead" status and use the match function but if it is dead it remains dead. In other words, I want to apply the match function (or any similar function that can do the same job) on this dataframe on all rows where "Status" is not equal to "Dead".
Upvotes: 0
Views: 1565
Reputation: 1959
Using @RonakShah dataframes and Tidyverse()
library(tidyverse)
Df1 <- data.frame(ID = 1:5,
Status = c('Injured', 'Dead', 'Dead', 'Alive', 'Injured'))
Df2 <- data.frame(Bird.ID = c(1, 3, 5))
Df1 <- Df1 %>%
mutate(Status = ifelse(ID %in% Df2$Bird.ID & Status != "Dead", "Alive", Status))
Upvotes: 1
Reputation: 388817
Well, it is easier to help if you share a small but reproducible example of your data. I created a sample dataset to demonstrate the solution.
Here's the data first.
Df1 <- data.frame(ID = 1:5,
Status = c('Injured', 'Dead', 'Dead', 'Alive', 'Injured'))
Df2 <- data.frame(Bird.ID = c(1, 3, 5))
Df1
# ID Status
#1 1 Injured
#2 2 Dead
#3 3 Dead
#4 4 Alive
#5 5 Injured
Df2
# Bird.ID
#1 1
#2 3
#3 5
Solution -
Df1$Status[Df1$ID %in% Df2$Bird.ID & Df1$Status != "Dead"] <- 'Alive'
Df1
# ID Status
#1 1 Alive
#2 2 Dead
#3 3 Dead
#4 4 Alive
#5 5 Alive
Upvotes: 2