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

时间:2014-09-08 17:20:47

标签: 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

我看到当我对我尝试过的新价值进行总结时,&#34;敌对 - IED攻击&#34;,我将所有内容都归还为NA&#39; s。我能够做一些类似于其他价值观的事情,但这一点并不容易。感谢。

1 个答案:

答案 0 :(得分: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)