创建新变量,其中 NA 对应于 0,非 NA 对应于 1 [英] Create new variable where NA correspond to 0 and non-NA to 1
本文介绍了创建新变量,其中 NA 对应于 0,非 NA 对应于 1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个值为 1
的新变量,如果不同的变量有任何非 NA
数字和 0
如果另一个变量是 NA
.
I am trying to create a new variable that has a value of 1
if a different variable has any, non-NA
number, and a 0
if the other variable is NA
.
因此变量具有如下值:
c(3, NA, 1, 2, NA)
...新变量应该是:
c(1, 0, 1, 1, 0)
我尝试使用 ifelse
,它可以将数字变成 1,但所有 NA
仍然是 NA
.
I tried to use ifelse
, and it worked to turn the numbers into a 1 but all the NA
s are still NA
s.
mydata$variable_presence <- ifelse(mydata$old_variable > 0, 1, 0)
我也试过对 NA
进行测试,但结果是一个错误.
I also tried testing for NA
but that just came up as an error.
mydata$variable_presense <- ifelse(mydata$old_variable = NA, 0, 1)
有什么建议吗?
推荐答案
简单的 is.na()
函数就可以了.R 中的布尔(逻辑)很容易被强制转换为二进制(1 表示真,0 表示假).
Simple is.na()
function will do.
Boolean (logical) in R can easily be coerced to binary (1 if true, 0 if false).
data = c(3, NA, 1, 2, NA)
as.numeric(!is.na(data))
会完成工作.
这篇关于创建新变量,其中 NA 对应于 0,非 NA 对应于 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文