Kuba_
Kuba_

Reputation: 814

optim function with a vector of parameters in R

I need to find a beta (3-element vector) which minimizes QRsum, defined as below:

#indicator function
I=function(x,min,max){
  if (min<=x && x<max){i=1} else {i=0}}

#QR check function
rho=function(a, theta){
  return(abs(theta-I(a,-Inf,0))*abs(a))
}

#QR sum
QRsum=function(beta,y,X,theta){
  sum=0
  for (i in 1:length(y)){
    sum=sum+rho(y[i]-t(X[i,])%*%beta,theta)
  }
  sum=1/length(y)*sum
  return(sum)
}

result=optim(initial_beta,QRsum(beta,y,X,0.05),method="BFGS")

Running optim function finished with following message:

Browse[1]> Q
> result=optim(initial_beta[1,],fn=QRsum(beta[1,],y,X,0.05),method="BFGS")
Error in (function (par)  : could not find function "fn"

Arguments of QRsum are y-a vector, X - a matrix with 3 columns and beta - a vector of 3 elements which should be optimized. QRsum function works fine when calling, but here it somehow fails. Is y and X are the objects I defined earlier or they are unknown also despite I defined them before? What should I put as first argument of my function - arbitrary value of a vector? I must say that I use optim for the very first time, so I suppose I'm missing something here, but I can't figure out what exactly based on help.

Upvotes: 0

Views: 2055

Answers (1)

tstudio
tstudio

Reputation: 307

You need to modify the call of the optim package to the following:

# define some data / value with which you want to use in the optimization
y_val <- ...
X_val <- ...
theta_val <- 0.05
# call optim / optimize beta with given values for y, X and theta
optim(par=initial_beta, fn=QRsum, y=y_val, X=X_val, theta=theta_val, method="BFGS")

Upvotes: 1

Related Questions