# [R] Code bug unresolved involving if condition

Thomas Lumley tlumley at u.washington.edu
Fri Apr 25 17:56:24 CEST 2003

```On Fri, 25 Apr 2003 vincent.stoliaroff at socgen.com wrote:

> Hi R lovers!
>
> I am a beginner in coding with R so my question may be very easily solved
> but I don't know how.
>
> I have written the following function in a .txt file
>
>
> ClearDelta <- function(Matrix)
> {
> ncol<-ncol(Matrix);nrow<-nrow(Matrix);
> for (i in 1:nrow) {
>                   for (j in 1:(ncol-1))
>                         {if (Matrix[i,j]==NA) (NA->Matrix[i,j+1])}
>                   }
> }
>
> I can charge it with the source() command
> But I get the following message when applied to a matrix
>
> > ClearDelta(MatCor)
> Error in if (Matrix[i, j] == NA) (Matrix[i, j + 1] <- NA) :
>         missing value where logical needed
>

>
> Do you know why I get such an unpleasant message from so polite a software?
>

The test (Matrix[i,j] ==NA) returns NA, not TRUE or FALSE as you expected.
Think of NA as meaning "I don't know what this value is", so you are
asking if Matrix[i,j] is equal to a number that you don't know. The answer
is that R doesn't know whether this is TRUE or FALSE, The value NA in a
logical variable means just that "This is TRUE or FALSE but I don't know
which".  You can use is.na() test for NA, ie

if(is.na(Matrix[i, j]))

I can't resist also pointing out that for large matrices there is a more
efficient answer

for(i in 1:nrow(Matrix))
Matrix[i,]<- diff(c(0,cumsum(Matrix[i,])))

-thomas

```

More information about the R-help mailing list