Hanna
Hanna

Reputation: 3

How to create a function with parameters and a loop inside in R?

I want to create vector of 365 elements equal to

fCAT[i]<-seasonality[i]+beta0+beta1*exp(-gamma*day[i])+beta2*gamma*exp(-gamma*day[i]) 

where beta0, beta1, beta2 and gamma are unknown parameters. Next I have to optimise the parameters by minimising (sum(fCAT)-1000)^2. I was thinking about using a loop inside a function but I don't know how to define it so that the parameters are interpreted correctly and not as strings. Any help will be appreciated.

Upvotes: 0

Views: 126

Answers (2)

pete
pete

Reputation: 2406

You can set up your function as:

f <- function(beta) {

    gamma <- beta[4]
    fCAT <- seasonality + beta[1] + 
        beta[2]*exp(-gamma*day) + 
        beta[3]*gamma*exp(-gamma*day)

    (sum(fCAT) - 1000)^2
}

Which you should be able to optimise using:

optim(rep(0, 4), f)

Upvotes: 1

Greg Snow
Greg Snow

Reputation: 49670

If fCAT and day are observed then this is just a non-linear least squares problem that you can use the nls function to solve.

Upvotes: 1

Related Questions