使用带有ifelse()的N来重新编码变量 [英] recode variables with NAs with ifelse() in R

查看:117
本文介绍了使用带有ifelse()的N来重新编码变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将两个二进制变量重新编码为新变量,以便第一个变量中的任何1在新变量中取0,并保留第二个变量中的所有数字。下面的代码显示了我想要生成的逻辑。但是,当我运行此代码时,使用ifelse()的重新编码只是重新创建x2而不包含使用x1的1为0的第一条ifelse()行。想法?

I am recoding two binary variables into new variable such that any 1s in the first variable take a 0 in the new one and all digits in the second variable are preserved. The code below shows the logic that I would like to produce. However, when I run this code, the recoding using the ifelse() just recreates x2 without incorporating the first ifelse() line that uses x1's 1s as 0. Thoughts?

set.seed(123)
x1 <- sample(c(0,1,NA), 20, replace = TRUE)
x2 <- sample(c(0,1,NA), 20, replace = TRUE)

recode <- ifelse(x1 == 1, 0, NA)
recode <- ifelse(x2 == 1, 1, recode)
recode <- ifelse(x2 == 0, 0, recode)

table(recode); table(x2)

谢谢

推荐答案

也许你想要这个?

ifelse(is.na(x2), ifelse(x1 == 1, 0, NA), x2)

这篇关于使用带有ifelse()的N来重新编码变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆