Jonsson
2015-Feb-13 09:59 UTC
[R] Why I am getting error when writing a function for "optim"?
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]))> funfunction(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.
S Ellison
2015-Feb-13 16:59 UTC
[R] Why I am getting error when writing a function for "optim"?
You don't appear to be supplying a valid parameter set to optim. The first argument in optim (par) must be a vector of parameters to optimise; you're passing a vector of NAs. Thise are not finite. Also, temp is defined as a value and optim will not be able to optimise that. You need to define temp as a function. S ******************************************************************* This email and any attachments are confidential. Any use...{{dropped:8}}