[R] Unexpected returned value from a function

p at fo76.org p at fo76.org
Wed Sep 17 00:50:35 CEST 2008


Quoting "Hutchinson,David [PYR]" <David.Hutchinson at ec.gc.ca>:

> I wrote a simple function to change values of a matrix or vector to NA
> based on the element value being -9999 or -999999. I don't understand
> why the function returns a unit vector (NA) instead of setting all
> values in the vector which have -9999 or -999999 to NA. When I apply the
> function in line, it appears to work correctly?
>
> Can someone enlighten me what I am doing wrong?

>   return ( values[ values == -9999 | values == -999999] <- NA )

the assignment itself evaluates to the assigned value, in this case NA;
that's what your function returns. Check this:

> foo <- (a <- 3)
> a
[1] 3
> foo
[1] 3
> foo <- (a <- NA)
> a
[1] NA
> foo
[1] NA

this way your function should work as intended:

ConvertMissingToNA <- function(values)
{
     values[ values == -9999 | values == -999999] <- NA
     return values
}

Peter



More information about the R-help mailing list