chars fregtun
chars fregtun

Reputation: 11

Maximization problem with R package nloptr

Good morning to everyone, I've a problem with a maximization with the R package nloptr. I've to maximize a correlation between a variable, call it "a", and a linear combination of other variables. Changing the weigths of the varibles in order to maximize the correlation. This is an example:

library(nloptr)
#create a dataset for the example

data=data.frame("a"=c(1:10), "b"=c(2,3,4,2,3,1,2,4,1,6), "c"=rep(c(10,15), 5))

#Objective Function
eval_f <- function(x,y)
{
return (cor(data$a,(xdata$b+ydata$c)))
}

eval_f(2,2)

#Equality constraints
eval_g_eq <- function(x,y)
{
return ( x+y-1 )
}

#Lower and upper bounds
lb <- c(0,0)
ub <- c(1,1)
#initial values
x0 <- c(0.5,0.5)

#Set optimization options.
local_opts <- list( "algorithm" = "NLOPT_LD_MMA", "xtol_rel" = 1.0e-15 )
opts <- list( "algorithm"= "NLOPT_GN_ISRES",
"xtol_rel"= 1.0e-15,
"maxeval"= 160000,
"local_opts" = local_opts,
"print_level" = 0 )
res <- nloptr ( x0 = x0,
eval_f = eval_f,
lb = lb,
ub = ub,
eval_g_eq = eval_g_eq,
opts = opts
)

This give me the error:

Error in .checkfunargs(eval_f, arglist, "eval_f") :
eval_f requires argument 'y' but this has not been passed to the 'nloptr' function.

Could someone help me?

Thanks.

Upvotes: 1

Views: 684

Answers (1)

Cettt
Cettt

Reputation: 11981

Instead of using a function f(x, y) use a function f(x) where x is a vector with two components:

eval_f <- function(x) cor(data$a,(x[1]*data$b+x[2]*data$c))
eval_g_eq <- function(x) sum(x) -1

lb <- c(0,0)
ub <- c(1,1)
x0 <- c(0.5,0.5)

local_opts <- list( "algorithm" = "NLOPT_LD_MMA", "xtol_rel" = 1.0e-15 )

opts <- list(
  "algorithm"= "NLOPT_GN_ISRES",
  "xtol_rel"= 1.0e-15,
  "maxeval"= 160000,
  "local_opts" = local_opts,
  "print_level" = 0 
)
res <- nloptr (
  x0 = x0,
  eval_f = eval_f,
  lb = lb,
  ub = ub,
  eval_g_eq = eval_g_eq,
  opts = opts
)

Upvotes: 1

Related Questions