[英]R $ operator is invalid for atomic vectors in constraOptim
I have a question here in how to implement constrOptim
: 我在这里有一个关于如何实现
constrOptim
:
The example from documentation goes as this: 文档中的示例如下:
fQP <- function(b) {-sum(c(0,5,0)*b)+0.5*sum(b*b)}
Amat <- matrix(c(-4,-3,0,2,1,0,0,-2,1), 3, 3)
bvec <- c(-8, 2, 0)
constrOptim(c(2,-1,-1), fQP, NULL, ui = t(Amat), ci = bvec)
However, when I just change the code to : 但是,当我只是将代码更改为:
fQP <- function(b) {-sum(c(0,5,0)*b)+0.5*sum(b*b)+c}
Amat <- matrix(c(-4,-3,0,2,1,0,0,-2,1), 3, 3)
bvec <- c(-8, 2, 0)
constrOptim(c(2,-1,-1), fQP, NULL, ui = t(Amat), ci = bvec,c=5)
An error occurs as: 出现错误:
Error:
$
operator is invalid for atomic vectors错误:
$
运算符对原子向量无效
Could anyone help me out? 任何人都可以帮我吗?
The error is stemming from the fact that the argument c=5
is matching the control
argument to the constrOptim
function, so this is the same as calling: 该错误源于参数
c=5
将control
参数与constrOptim
函数匹配的constrOptim
,因此这与调用相同:
constrOptim(c(2,-1,-1), fQP, NULL, ui = t(Amat), ci = bvec,control=5)
# Error: $ operator is invalid for atomic vectors
The control
parameter expects to be passed a list but is being passed 5
instead, so when it tries to access elements it raises this error. control
参数希望传递一个列表,但是传递的是5
,所以当它尝试访问元素时会引发这个错误。
To make this setup work, you need to explicitly state that c
is an argument to your function (and further change it to a name that won't conflict with the built-in c
function, which you also use in that function): 要使此设置有效,您需要明确声明
c
是函数的参数(并进一步将其更改为与内置c
函数不冲突的名称,您也在该函数中使用该函数):
fQP <- function(b, c2) {-sum(c(0,5,0)*b)+0.5*sum(b*b)+c2}
Amat <- matrix(c(-4,-3,0,2,1,0,0,-2,1), 3, 3)
bvec <- c(-8, 2, 0)
constrOptim(c(2,-1,-1), fQP, NULL, ui = t(Amat), ci = bvec,c2=5)
# $par
# [1] 0.4762222 1.0475556 2.0951112
#
# $value
# [1] 2.619048
#
# $counts
# function gradient
# 506 NA
#
# $convergence
# [1] 0
#
# $message
# NULL
#
# $outer.iterations
# [1] 3
#
# $barrier.value
# [1] -0.0006243968
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.