R $ 运算符对 constraOptim 中的原子向量无效 [英] R $ operator is invalid for atomic vectors in constraOptim
问题描述
我有一个关于如何实现 constrOptim
的问题:
I have a question here in how to implement constrOptim
:
文档中的示例如下:
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)
出现以下错误:
错误:$
运算符对原子向量无效
Error:
$
operator is invalid for atomic vectors
谁能帮帮我?
推荐答案
该错误源于以下事实:参数 c=5
与 control
参数匹配constrOptim
函数,所以这与调用相同:
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:
constrOptim(c(2,-1,-1), fQP, NULL, ui = t(Amat), ci = bvec,control=5)
# Error: $ operator is invalid for atomic vectors
control
参数期望传递一个列表,但实际上传递的是 5
,因此当它尝试访问元素时会引发此错误.
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.
要使此设置工作,您需要明确声明 c
是您函数的参数(并进一步将其更改为不会与内置 c
函数,您也在该函数中使用):
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):
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
这篇关于R $ 运算符对 constraOptim 中的原子向量无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!