mardi 24 avril 2018

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:

  • If Pl1 == Pl2 then desired output is 0 for the forth column
  • If Pl1 == NA then desired output is NA for the forth column
  • for the conditions which should be logically where Pl1 != Pl2, then desired output is 1 for the forth column.

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?

Aucun commentaire:

Enregistrer un commentaire