使用 ifelse 将 NA 替换为零

Replace NAs with zeros using ifelse

我正在尝试用零替换我的名为 violence 的变量中的 NA,并使用 ifelse 创建一个新的虚拟变量。暴力变量有几个类别和 NA。类别忽略应编码为 1,但其他类别(包括 NA)应编码为 0。我使用以下代码:

   df$new_variable<-ifelse(is.na(df$violence)=="ignore",1,0)

但是,代码没有产生任何结果。

代码中存在语法问题

is.na(df$violence) == "ignore"

将从 is.na 派生的逻辑列与“忽略”进行比较,如果描述如 OP 的 post - The category ignore should be coded 1 but other categories including NAs should be coded 0. 中所述,则使用

df$new_variable <- +(df$violence %in% "ignore")

在这里,我们用 %in% 检查“忽略”的值,其中 returns 一个逻辑向量 - TRUE 仅用于“忽略”,FALSE 用于所有其他包括 NA== returns NA 用于 NA 值)然后使用 + 转换为二进制(TRUE -> 1FALSE -> 0)