在R中从nloptr的输出写入CSV文件

在R中从nloptr的输出写入CSV文件,r,R,我想把nloptr输出的变量的最佳值写在R中。例如,我有这个程序,如何从res中获得x向量的最佳值,并将其打印在CSV文件中 library('nloptr') eval_f <- function( x ) { yx = x[1]*x[4]*(x[1] + x[2] + x[3]) + x[3]; return( list( "objective" = yx, "gradient" = c( x[1] * x[4] + x[4] * (x[1] +

我想把nloptr输出的变量的最佳值写在R中。例如,我有这个程序,如何从res中获得x向量的最佳值,并将其打印在CSV文件中

library('nloptr')
eval_f <- function( x ) {
  yx = x[1]*x[4]*(x[1] + x[2] + x[3]) + x[3];
  return( list( "objective" = yx,
                "gradient" = c( x[1] * x[4] + x[4] * (x[1] + x[2] + x[3]),
                                x[1] * x[4],
                                x[1] * x[4] + 1.0,
                                x[1] * (x[1] + x[2] + x[3]) ) ) );
}
local_opts <- list( "algorithm" = "NLOPT_LD_MMA",
                    "xtol_rel" = 1.0e-7 );

opts <- list( "algorithm" = "NLOPT_LD_AUGLAG",
              "xtol_rel" = 1.0e-7,
              "maxeval" = 1000,
              "local_opts" = local_opts );

x0 <- c( 1, 5, 5, 1 );
lb <- c( 1, 1, 1, 1 );
ub <- c( 5, 5, 5, 5 );
res <- nloptr( x0=x0, eval_f=eval_f,lb=lb,ub=ub,opts=opts);
print(res)
我想将向量[1,1,1,1]写入csv文件。如何做到这一点? 谢谢

函数返回一个列表,其中一个元素是 (
$solution
)是所需值的向量

因此,如果
res
如上所示:

# ...
x0 <- c(1, 5, 5, 1)
lb <- c(1, 1, 1, 1)
ub <- c(5, 5, 5, 5)
res <- nloptr(x0=x0, eval_f=eval_f, lb=lb, ub=ub, opts=opts)
然后提取所需的值并将其写入csv(如果您需要该格式):

values函数返回一个列表,其中一个元素
(
$solution
)是所需值的向量

因此,如果
res
如上所示:

# ...
x0 <- c(1, 5, 5, 1)
lb <- c(1, 1, 1, 1)
ub <- c(5, 5, 5, 5)
res <- nloptr(x0=x0, eval_f=eval_f, lb=lb, ub=ub, opts=opts)
然后提取所需的值并将其写入csv(如果您需要该格式):

str(res)
## ...
## $ iterations            : int 6
## $ objective             : num 4
## $ solution              : num [1:4] 1 1 1 1     <~~~ the thing we want
## $ version               : chr "2.4.2"
## - attr(*, "class")= chr "nloptr"
values <- res$solution
write.csv(values, "nloptr_soln.csv", row.names=FALSE)