在rpy2中配置nlme::lme的corAR1相关性参数时遇公式错误求助
问题背景
目标是用rpy2实现R语言中nlme::lme模型,对应R代码如下:
fit <- nlme::lme(y ~ T + t, random = ~ 1 | sub, correlation = corAR1( form = ~ 1 | sub))
已成功运行不含correlation参数的模型:
formula = robjects.Formula('y0 ~ T + t + c0') random = robjects.Formula('~1|sub') m1 = nlme.lme(formula,random=random, data=endogexog)
但添加correlation参数指定AR1结构时触发错误,执行代码:
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)
in
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
682RRuntimeError: Error in formula.default(object) : invalid formula
错误原因
核心问题是给nlme.corAR1()的form参数传递了robjects.Formula对象,而非原生字符串公式。
R的corAR1()函数需要的是原生公式表达式,但rpy2的robjects.Formula是封装后的Python对象,传递到R端后无法被formula.default()函数解析,因此触发"invalid formula"错误。
修正方案
直接传入字符串格式的公式即可,无需用robjects.Formula包装:
m2 = nlme.lme(formula, random=random, correlation=nlme.corAR1(form="~1|sub"), data=endogexog)
内容的提问来源于stack exchange,提问作者Lasse Meixner

