How to avoid RRuntimeError when calling R stats.optim function within python using rpy2?

Viewed 106

I am trying to call stats.optim R function within python using rpy2. However, I encountered the following error:

RRuntimeError: Error in (function (par, fn, gr = NULL, ..., method = c("Nelder-Mead",  : objective function in optim evaluates to length 0 not 1

I have mostly followed the optim function example from here : http://rpy.sourceforge.net/rpy2/doc-2.2/html/rinterface.html). See section "Calling Python functions from R" Here is my code:

from rpy2.robjects import r
import rpy2.robjects as robjects
import rpy2.rinterface as ri


# Function to be optimized, v1 is a 1-dimensional numpy array and m1 is n 
# by 3 numpy matrix
def f(beta):
    return np.sum(np.square((np.divide(v1,np.matmul(m1,beta))-1)))

# convert python function to R function
r_f = ri.rternalize(f)

Beta =  robjects.FloatVector((0,1,0))
res = r.optim(Beta, r_f)

I made sure the function f being defined was correct and could be converted to an r function object. When I call r_f(Beta) for example, it returns a correct result. I am wondering if there is a way to avoid such a problem. I just learnt about rpy2 and any advice is appreciated! Thank you in advance

1 Answers

This is likely because your objective function failing as np, v1, and m1 are not defined.

There is also likely a buglet in rpy2 as the error should normally make their way as warnings of some sort.

Related