Gradient function for constrOptim in R

r

#1

Hi I’m trying to solve the following but error shows Error in f(theta, …) - mu * bar : non-numeric argument to binary operator.
can anyone help? Thank you in advance.

f = function(x) {
function(theta){
p = theta[1]
q = theta[2]
2x^2p - 5q^2 - 4p^2 - x^4 - 2*q^4
}
}

g = function(theta, x) {
p = theta[1]
q = theta[2]
h = expression(2x^2p - 5q^2 - 4p^2 - x^4 - 2*q^4)
dp = D(h, “p”)
dq = D(h, “q”)
return(c(dp, dq))
}
constrOptim(c(3,1), f, g, ui=matrix(c(1,1,0,-1), nrow=2), ci=c(0,0),hessian = TRUE)


#2

I think the issue is in the f function. There’s no need to have nested functions. Try the code below:

f = function(theta, x) {

p = theta[1]
q = theta[2]

2 *x^2* p - 5 *q^2 - 4* p^2 - x^4 - 2*q^4

}