probably a stupid question but I clearly can't see it and would appreciate your help.
Here is a fictional dataset:
dat <- data.frame(ID = c(101, 202, 303, 404),
var1 = c(1, NA, 0, 1),
var2 = c(NA, NA, 0, 1))
now I need to create a variable that sums the values up, per subject. The following works but ignores when var1 and var2 are NA:
try1 <- apply(dat[,c(2:3)], MARGIN=1, function(x) {sum(x==1, na.rm=TRUE)})
I would like the script to write NA if both var1 and var2 are NA, but if one of the two variables has an actual value, I'd like the script to treat the NA as 0. I have tried this:
check1 <- apply(dat[,2:3], MARGIN=1, function(x)
{ifelse(x== is.na(dat$var1) & is.na(dat$var2), NA, {sum(x==1, na.rm=TRUE)})})
This, however, produces a 4x4 matrix (int[1:4,1:4]). The real dataset has hundreds of observations so that just became a mess...Does anybody see where I go wrong?
Thank you!
question from:
https://stackoverflow.com/questions/65939225/apply-with-ifelse-statement-and-is-na-does-not-sum-but-outputs-matrix-where 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…