Rsolnp: In cbind(temp, funv) : number of rows of result is not a multiple of vector length (arg 1)

你说的曾经没有我的故事 提交于 2019-12-05 18:17:49

Welcome to SO.

You got two issues here a) problem w.r.t the result and b) a warning message you can't make any sense of.

ad a) This is simply because LaGrange optimization is often done by minimizing a negative value instead of maximizing a positive value. That's been the difference. When setting d to -d (I did so in the edit) the solution is the same as the solution produced by other solvers.

ad b) the warning message issue is somewhat tricky. The message itself means that cbind tries to bind two columns of different length. What R does is it repeats the values in the shorter column as often as necessary to get two columns of equal length to bind. If the longer is not a multiple of the shorter you get this warning, but R continues to repeat values of the shorter if it means there's some unused remainder.

However, it looks like there's a bug in the package. When you run

options(warn = 2) # turns warnings to errors and breaks code
debug(solnp)
sol <- solnp(pars = x0, 
     fun = fn, 
     eqfun = sum, 
     eqB = 1, 
     ineqLB = lx, 
     ineqUB = ux)

you realize that there is an object called tempdf being created that causes the problem. However, this object is never used again in the code of solnp. I'll ask the authors, maybe they can confirm this is a bug or show otherwise.

Make the result of your objective function, fn, explicitly numeric:

fn <- function(x){
  d <- c(0.0308, 0.0269, 0.0145, 0.0130)
  d <- -d
  D <- cbind(c(0.1486, 0.0778, -0.0240, -0.0154), 
             c(0.0778, 0.1170, 0.0066, 0.0029), 
             c(-0.0240, 0.0066, 0.0444, 0.0193), 
             c(-0.0154, 0.0029, 0.0193, 0.0148))
  out <- t(d) %*% x + 0.5 * (t(x) %*% D %*% x)
  as.numeric(out)
}

and I get

Iter: 1 fn: -0.01153 Pars: 0.24798607502 0.00000002295 0.01205720515 0.73995669928 Iter: 2 fn: -0.01153 Pars: 0.247984418270 0.000000003318 0.012080555874 0.739935021900 solnp--> Completed in 2 iterations

sol$pars [1] 2.479844e-01 3.317577e-09 1.208056e-02 7.399350e-01

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!