简体   繁体   中英

rpy2: represent NA in Python as an argument to R function

I'm trying to pass an NA to R function, eg, make predictions with a lme4 mixed model using only fixed effects (ie, without random effects):

import rpy2.rinterface as ri
from rpy2.robjects.packages import importr
rstats = importr('stats')
rstats.predict( mymodel, re_form=ri.NA_Logical )

However, re_form=ri.NA_Logical fails to pass NA to re.form (I've tried also aliases REform , ReForm , etc.), for some reason. Any ideas?

This R function: https://www.rdocumentation.org/packages/lme4/versions/1.1-20/topics/predict.merMod

This might be an issue with function dispatch / ellipsis in the signature of the generic (if an ellipsis is used in the signature of the generic rpy2 has no way to know that it should translate . to _ for a yet-unknown named argument).

Try:

rstats.predict(mymodel, **{'re.form': ri.NA_Logical})

or:

lme4 = importr('lme4')
lme4.predict_merMod(mymodel, re_form=ri.NA_Logical)

Relevant sections in the doc are https://rpy2.github.io/doc/v3.0.x/html/robjects_rpackages.html#importing-r-packages and https://rpy2.github.io/doc/v3.0.x/html/robjects_functions.html#rpy2.robjects.functions.SignatureTranslatedFunction (the latter mostly means that the doc is the code).

edit:

It is also possible to mix R code with Python a creative way. For example:

myfunc = robjects.r('function (x) predict.merMod(x, re.form=NA)')
myfunc(mymodel)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM