How to use correlation argument of nlme model in rpy2

84 views Asked by At

I want to estimate the model

fit <- nlme::lme(y ~ T + t, random = ~ 1 | sub, correlation = corAR1( form = ~ 1 | sub))

in rpy2. I am running the following without problems:

formula = robjects.Formula('y0 ~ T + t + c0')
random = robjects.Formula('~1|sub')
m1 = nlme.lme(formula,random=random, data=endogexog)

where endogexog is my corresponding data.

However, when I want to specify the ar1 structure of errors within subject through the correlation argument, I get an error.

correlation_formula = robjects.Formula("~ 1|sub")
m2 = nlme.lme(formula,random=random, correlation=nlme.corAR1(form=correlation_formula), data=endogexog)
WARNING:rpy2.rinterface_lib.callbacks:R[write to console]: Error in formula.default(object) : invalid formula

---------------------------------------------------------------------------
RRuntimeError                             Traceback (most recent call last)
<ipython-input-26-3653905f35ef> in <module>
      3 # The general idea is right, see https://stackoverflow.com/questions/17333351/correlation-structure-corar1-not-defined-in-rpy2-generalised-least-squares-m
      4 # how to pass it correctly with correlation argument specified?
----> 5 m2 = nlme.lme(formula,random=random, correlation=nlme.corAR1(form=correlation_formula), data=endogexog)

3 frames
/usr/local/lib/python3.7/dist-packages/rpy2/rinterface.py in __call__(self, *args, **kwargs)
    678             )
    679             if error_occured[0]:
--> 680                 raise embedded.RRuntimeError(_rinterface._geterrmessage())
    681         return res
    682 

RRuntimeError: Error in formula.default(object) : invalid formula

Any idea why this could be?

1

There are 1 answers

1
kesh On

Try using stats.asOneSidedFormula

from rpy2.robjects.packages import importr

stats = importr('stats')

# correlation_formula = robjects.Formula("~ 1|sub")
correlation_formula = stats.asOneSidedFormula("~ 1|sub")