Reputation: 103
I have a question here in how to implement 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?
Upvotes: 1
Views: 1138
Reputation: 44299
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
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.
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
Upvotes: 3