I have created the variable np_collpar with the following code
a <- c(NA,NA,NA,1,1,1)
c1 <- c(9,3,NA,NA,NA,5)
c2 <- c(5,NA,NA,NA,5,2)
c3 <- c(3,7,NA,NA,NA,9)
df <- data.frame(a,c1,c2,c3)
np_collpar <- ifelse(a==1 & (!is.na(c1) | !is.na(c2) | !is.na(c3)),1,0)
I want np_collpar to be 1 for rows 5 and 6 and 0 for rows 1-4. However, NA is returned for rows 1 and 2. The Boolean reasoning behing the ifelse statement should be correct. Could anyone give me a hint? Thanks.
You need to specify what happens if a
is NA
. Add (!is.na(a))
like below.
> np_collpar <- ifelse(a==1 & (!is.na(a)) & (!is.na(c1) | !is.na(c2) | !is.na(c3)),1,0)
> np_collpar
[1] 0 0 0 0 1 1
Other option using complete.cases()
, which returns FALSE
if the vector has an NA
, and TRUE
otherwise.
np_collpar <- ifelse(a==1 & (complete.cases(a)) & (complete.cases(c1) | complete.cases(c2) | complete.cases(c3)), 1, 0)
np_collpar
[1] 0 0 0 0 1 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.