[R] Why I am getting error when writing a function for "optim"?

Jonsson amen.alyaari at Bordeaux.inra.fr
Fri Feb 13 10:59:20 CET 2015


I have three directories where there is inside each of them 5 files.each file
is a matrix lines 500 and columns 300. I want to perform an optimization
using values from three corresponding pixels.Finally I get a matrix of lines
500 and columns 300 for each parameter in my equation:

           y=(ax1+bx2+c)^2+d
reproducible example:

  dat1 <- array(1:60, c(3,5,4));dat2 <- array(rnorm(60), c(3,5,4));
  dat3 <-array(rnorm(60), c(3,5,4))
reorder dimensions

   dat1 <- aperm(dat1, c(3,1,2));dat2 <- aperm(dat2, c(3,1,2));
   dat3 <- aperm(dat2, c(3,1,2))
make array a matrix

  dat1a <- dat1  ; dim(dat1a) <- c(dim(dat1)[1],prod(dim(dat1)[2:3]))
  dat2a <- dat2;  dim(dat2a) <- c(dim(dat2)[1],prod(dim(dat2)[2:3]))
  dat3a <- dat3 ; dim(dat3a) <- c(dim(dat3)[1],prod(dim(dat3)[2:3]))

> fun
function(x1,x2, y) {
  keep <- !(is.na(x) | is.na(x2)| is.na(y))
  if (sum(keep) > 2) { #less than 3 non-NA values?
    temp <- sum((y[keep] - (p[1]*x1[keep]+p[2]*x2[keep]+p[3])^p[4]+p[5])^2)
    res <- optim(rep(NA,5),temp)
  } else {
    res <- c(NA, NA,NA,NA,NA)#five parameters
  }
 res
}
> res <- mapply(fun, x1=as.data.frame(dat1a), x2=as.data.frame(dat2a),
> y=as.data.frame(dat3a)) 
Error in optim(rep(NA, 5), temp) : non-finite value supplied by optim

Any idea please on how to correct my function?



--
View this message in context: http://r.789695.n4.nabble.com/Why-I-am-getting-error-when-writing-a-function-for-optim-tp4703205.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list