Correlation structure corAR1() "not defined" in rpy2 generalised least squares model gls

StackOverflow https://stackoverflow.com/questions/17333351

  •  01-06-2022
  •  | 
  •  

Question

I'm using the rpy2 module in python to calculate regressions between two timeseries (ts1 and ts2). The residuals are autocorrelated, so I need to use the gls model rather than lm. I should be able to set my correlation structure as corAR1() as in the code below.

import rpy2.robjects as robjects
from rpy2.robjects import FloatVector
from rpy2.robjects.packages import importr

nlme = importr('nlme')

y = FloatVector(ts1)
x = FloatVector(ts2)
fmla = robjects.Formula('y ~ x - 1')
env = fmla.environment
env['x'] = x
env['y'] = y
fit = nlme.gls(fmla, cor=corAR1(value=c(0.5)))  

However, I get the error

*** NameError: name 'corAR1' is not defined                                                                                                      

As I'm not an R user and very new to rpy2, I'm not sure what's going on here! Any ideas would be much appreciated.

Cheers, Felicity

Was it helpful?

Solution

when calling importr('nlme'), the object returned is like a Python package/namespace. If corAR1() is defined in the nlme package, you should tell Python that it is there:

fit = nlme.gls(fmla, cor=nlme.corAR1(value=c(0.5)))  
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top