I would like to minimize a function with two variables.
First I have made a function (rba)
, which is needed inside the function (kvasum)
that I need to minimize. The values to minimized over are a part of rba
.
# Data
vpk = data.frame(V1 =c(3650000000, 19233, 2211.2, 479.47, 168.46, 83.447, 52.349, 38.738,
32.34, 29.588), V2 = 1:10)
n = nrow(vpk)
# functions to minimize
# This function returns a vector with 10 values
rba = function(par){
v <- matrix(ncol = 1, nrow = 10)
for (p in 1:10){
k<- ifelse (par[1] < 1-1/p && par[1]>0 && p > par[2] &&
par[2]>0 && par[2]<2, par[2]*p,
ifelse(par[1] < 1-1/par[2] && par[1] > 0 &&
p < par[2] && par[2]>0 && par[2]<2, -1+(par[1]+1/par[2]),
ifelse(par[1] > (1 - 1 / max(p,par[2])) &&
par[2]>0 && par[2]<2, -1+p, "error")))
v[p] <- k
}
return(v)
}
# This function uses the function rba, and returns a value
kvasum = function(par){
sum( (log(vpk$V1)/log(1/n) - rba(par) )^2)
}
# what I would I to do is to find par[1] and par[2] such that kvasum is minimized
m1 = optim(par=c(0.1,0.4),kvasum, lower=0)
I've tried to use the optim function, but I can't get it to work. I get a non-numeric argument, and have tried everything I can think of. Any help is appreciated.