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

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to