DSA
DSA

Reputation: 721

Error: missing value where TRUE/FALSE needed when there is no NA value fitted in R

I have been checking here to find a similar problem and I couldn't see, even though I saw the same error message.

So let say I have a data:

temp = data.frame(ID = c(1:5),
Pl = c("11","12",NA,"14",NA), Pl2 = c("11","11","12","14","14"))
ID   Pl Pl2
 1   11  11
 2   12  11
 3 <NA>  12
 4   14  14
 5 <NA>  14`

And I wanted to create the fourth column with the conditions:

In the end, I came up with this code which I got the error message:

for (i in nrow(temp)){
  if (temp[i,2] == temp[i,3]) { 
    temp[i,4] = "0"
  } else if (is.na(temp[i,2])) {
    temp[i,4] = NA
  } else (temp[i,4] = "1")
}

Error in if (temp[i, 2] == temp[i, 3]) { : 
  missing value where TRUE/FALSE needed

So I can't see the any syntax/operator error but there might be some logical thing?

Upvotes: 2

Views: 116

Answers (1)

akrun
akrun

Reputation: 887153

We can just do a comparison and coerce it to binary

with(temp, as.integer(Pl != Pl2))

Or

with(temp, as.integer(!(NA^(is.na(Pl))* (Pl == Pl2)))) 

In the OP'code, the it is looping through nrow i.e. a single number instead it should be either 1:nrow(temp) or more correct seq_len(nrow(temp))

for (i in 1:nrow(temp)){
  if (temp[i,2] == temp[i,3] & !is.na(temp[i,2])) { 
    temp[i,4] <- "0"
  }else if (is.na(temp[i,2])){
   temp[i,4] <- NA
   } else {
     temp[i,4] <- "1"
   }

}

temp[,4]
#[1] "0" "1" NA  "0" NA 

Upvotes: 2

Related Questions