Nazer - 1 year ago 96

R Question

I would like to find the best parameters to fit a curve to my data and I feel like I have everything set up pretty well, but when I run my optimization function, I just get back the starting parameters.

`rick<-function(x, a, b){`

x*a*exp(-x/b)

}

x<-df$WaterInput

a<-.1

b<-460

pred<- rick(t, a, b)

predD<-as.data.frame(pred)

predD$WI<-df$WaterInput

plot(WUEs~WaterInput, data=df)

points(predD$WI, predD$pred, type="p", col="red")

### Optimization attempt###

obfun<- function(coef, x){

sim<- rick(x=x, a=coef[1], b=coef[2])

simD<-as.data.frame(pred)

simD$day<-df$WaterInput

obs<- df$WUEs

rss <- sum((obs - simD$pred)^2)

rss

}

op.wi<- optim(c(.1, 460), obfun, x=df$WaterInput)

The dataframe can be found here: https://www.dropbox.com/s/kns2h2zcqtagwns/WUE%20for%20SO.txt?dl=0

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

That's simply because you don't use the coefficients in your optimization. Right now you are calling `rick()`

, then assigning the returned value to `sim`

, but then you do not use it in your objective function, `rss`

. Also you have a `t`

in your example, that you didn't supply.

I think you want something like:

```
rick <- function(x, a, b){
x*a*exp(-x/b)
}
x <- df$WaterInput
a <- .1
b <- 460
pred <- rick(x, a, b)
predD <- as.data.frame(pred)
predD$WI <- df$WaterInput
plot(WUEs~WaterInput, data=df)
points(predD$WI, predD$pred, type="p", col="red")
obfun <- function(coef, x){
sim <- rick(x=x, a=coef[1], b=coef[2])
obs <- df$WUEs
rss <- sum((obs - sim)^2)
rss
}
op.wi <- optim(c(.2, 460), obfun, x=df$WaterInput)
points(x, rick(x, op.wi$par[1], op.wi$par[2]),col=3)
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**