无效的因子水平,生成NA警告。

4

与这里提出的另一个问题类似,我收到了主题行中的错误消息。我试图使用它的解决方法来解决我的问题,但我无法做到这一点。这是我的代码:

#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

当我总结我的尝试新值“Hostile-IED Attack”时,我发现所有的返回值都是NA。我能做类似的事情来处理其他值,但这一个不那么容易。谢谢。


4
当使用read.tableread.csv读取数据时,需使用stringsAsFactors=FALSE,以避免将字符向量转换为因子(factor)。 - akrun
1个回答

7

首先将其转换为因子,进行更改后再重新转换回来。此外,在长期运行中 %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)

1
你不需要列出每个次要原因。使用grep主要的COD可能更快。USdata$Cause[grep("IED attack",USdata$Cause),] <- "Hostile - IED Attack" - Brandon Bertelsen
1
不了解底层数据,我不想对海报所使用的内容做任何假设,但如果它确实是统一的,你的方法绝对正确。这是更好的方法。 - hrbrmstr
1
这不是批评:)评论是针对OP的。 - Brandon Bertelsen
好的,我理解了(并相应修改了我的评论 :-) - hrbrmstr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接