因子级别无效,NA生成警告

Sea*_*arp 2 r

与此处提出的另一个问题类似,我在主题行中收到错误消息.我试图使用它的补救措施来解决我的问题,但我无法这样做.这是我的代码:

#Change the format of IED deaths to be uniform
USdata$Cause[USdata$Cause=="Hostile - hostile fire - IED attack" | USdata$Cause=="Hostile - hostile fire - IED attack (suicide attack)" | USdata$Cause=="Hostile - hostile fire - IED attack (suicide car bomb)" | USdata$Cause=="Hostile - hostile fire - IED attack (while defusing)" | USdata$Cause=="Hostile - hostile fire - IED attack, RPG" | USdata$Cause=="Hostile - hostile fire - IED attack, RPG, small arms fire" | USdata$Cause=="Hostile - hostile fire - IED Attack, small arms fire" | USdata$Cause=="Hostile - hostile fire - IED Attack, small arms fire, indirect fire"] <- "Hostile - IED Attack"

Warning message:
In `[<-.factor`(`*tmp*`, USdata$Cause == "Hostile - hostile fire - IED attack" |  :
 invalid factor level, NA generated
Run Code Online (Sandbox Code Playgroud)

我看到当我对我尝试过的新值"Hostile - IED Attack"进行总结时,我将所有内容都返回为NA.我能够做一些类似于其他值的事情但是这个并不那么容易.谢谢.

hrb*_*str 5

首先从一个因子转换它,进行更改并重新转换它.此外,%in%从长远来看,可能对您更有效:

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)
Run Code Online (Sandbox Code Playgroud)