r - Perform operation on subset of factors -
i have factor variable, condition, tells me whether subjects took test or not:
data$condition.f <- factor(data$condition, labels = c("notest", "test"))
i have variable, x contains right (1) , wrong (0) responses question.
> data$x [1] na na na na na na na na na na na na na na na na na na na na na na na na na na na na na na na na na na na na na na na na na [42] na na na na na na na na na na na na na na na na na na na na na na na 1 1 1 na na 1 0 na 1 1 1 0 0 0 1 0 1 0 [83] 1 1 0 1 na 1 0 1 1 1 1 1 na 1 na 0 1 1 1 0 1 0 1 1 0 na 1 1 1 1 1 1 0 1 na 1 0 0
the first half of vector corresponds did not take test (hence nas), , remainder represent did take test.
i replace nas did take test 0. have tried following code:
if (data$condition.f == "test") { data$x[which(is.na(data$x))] <- 0 }
but error
warning message: in if (data$condition.f == "test") { : condition has length > 1 , first element used
i'm not sure exact issue is, although know has if statement. there better way replace nas 0 took test?
thank you
your problem arises because trying compare vector (data$condition.f
) string ("test"
).
how data$x[is.na(data$x) & data$condition.f == "test"] <- 0
instead?
edit: fixed mistake upon thelatemail's suggestion below.