[R] Substitute "Object not found" with NA

Duncan Murdoch murdoch at stats.uwo.ca
Fri Dec 4 13:03:30 CET 2009


Veronesi, Fabio wrote:
> Hi everybody,
> I'm trying to create a script that picks a txt file with 2 columns of coordinates (depth and variable1) and automatically tries to fit several polynomial with the function nls().
> After  that, it creates a list of observed, predict, residuals and other, and then it calculates AIC, RMSD, MAD and R^2.
> At the end of the script I create a series of vectors with MAD for all polynomials, RMSD for all polynomial and so on, and from a matrix a .csv file.
> This script is completely automatic, but there is a problem if one or more models don't fit, because if one or more data is missing I cannot create the vectors and the matrix, as well.
>
> So, my question is: is it possible to create a vector with a missing object, substituting that object with NA in the vector?
>
> For example:
> I want to create this vector
> Vec1<-c(MAD1,MAD2,MAD3,MAD4)
> but MAD4 is missing and as a consequence R return an error like this:
> "object 'MAD4' not found"
>
> Is it possible to say to R that if it does not find an object it must substitute that object with NA in the vector?
>
>   
Not automatically, but you can write an expression to do that:

if (exists("MAD4")) MAD4 else NA

or

tryCatch(MAD4, error=function(e) NA)


You could write a function to do this.  I wouldn't recommend trying the 
first version; it will be messy.  But the second is:

defaultNA <- function(x) {
  tryCatch(x, error=function(e) NA)
}

then defaultNA(MAD4) will do what you want. 

Duncan Murdoch




More information about the R-help mailing list