r - Minimize a function with two variables -
i minimize function 2 variables.
first have made function (rba)
, needed inside function (kvasum)
need minimize. values minimized on 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 minimize # function returns vector 10 values rba = function(par){ v <- matrix(ncol = 1, nrow = 10) (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) } # function uses function rba, , returns value kvasum = function(par){ sum( (log(vpk$v1)/log(1/n) - rba(par) )^2) } # find par[1] , par[2] such kvasum minimized m1 = optim(par=c(0.1,0.4),kvasum, lower=0)
i've tried use optim function, can't work. non-numeric argument, , have tried can think of. appreciated.
there few problems overall process cause trouble.
first of @user227710 mentions in comments should replace &&
&
. these have different meanings.
now optimiser
it looks want set limits parameters (i.e. known box constraints). in order , use lower
argument, need use l-bfgs-b
method. when use need specify upper
argument well.
the error receive, receive because ifelse
statement works when values between 0 , 1 roughly. otherwise, k variable gets value error
(which value returned if conditions in ifelse
statements false) why
error in log(vpk$v1)/log(1/n) - rba(par) : non-numeric argument binary operator
error.
therefore, if specify box constraints accordingly (or maybe have @ ifelse statement because might have coded wrong) seems work perfect:
# 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 minimize # function returns vector 10 values rba = function(par){ v <- matrix(ncol = 1, nrow = 10) (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"))) #i adding line here know why optim failed if(k=='error') stop('your ifelse function returned error') v[p] <- k } return(v) } # function uses function rba, , returns value kvasum = function(par){ sum( (log(vpk$v1)/log(1/n) - rba(par) )^2) } # find par[1] , par[2] such kvasum minimized m1 = optim(par=c(0.1,0.4),kvasum, method='l-bfgs-b', lower= c(0.1,0.1), upper=c(0.9,0.9))
output:
> m1 $par [1] 0.1 0.1 $value [1] 171.5774 $counts function gradient 2 2 $convergence [1] 0 $message [1] "convergence: norm of projected gradient <= pgtol"
Comments
Post a Comment