Invalid factor level, NA generated warning

Convert it from a factor first, do the change and re-convert it back. Also, %in% might work better for you in the long run:

ied_causes <- c("Hostile - hostile fire - IED attack",
                "Hostile - hostile fire - IED attack (suicide attack)",
                "Hostile - hostile fire - IED attack (suicide car bomb)",
                "Hostile - hostile fire - IED attack (while defusing)",
                "Hostile - hostile fire - IED attack, RPG",
                "Hostile - hostile fire - IED attack, RPG, small arms fire",
                "Hostile - hostile fire - IED Attack, small arms fire",
                "Hostile - hostile fire - IED Attack, small arms fire, indirect fire")

USdata$Cause <- as.character(USdata$Cause)
USdata$Cause[USdata$Cause %in% ied_causes] <- "Hostile - IED Attack"
USdata$Cause <- factor(USdata$Cause)

Leave a Comment