mardi 22 décembre 2020

Testing Vector for equality with NAs in subscripts R

I discovered a strange behavior in R and wanted to ask whether it can lead to problems. Here is an example of what I mean:

x<-c(1,2,3,4,NA, 5)
x==1
x

this returns:

TRUE FALSE FALSE FALSE    NA FALSE

Now say I want to change all x==1 to 100:

x[x==1]<-100
x

returns:

100   2   3   4  NA   5

So for some reason referencing x with a logical vector with an NA worked. Why? To me this behavior of "==" with NAs doesn't make much sense. I am also worried now that this kind of assignment x[x==y]<-... may have caused (unnoticed) problems with other types of vectors such as in data.frames or matrices. Has anyone encountered any problems with this or does this logical NA referencing work consistently with other types of vectors?

Aucun commentaire:

Enregistrer un commentaire