How to give R's "matchit" a formula object via Python's r2py?

Viewed 31

I use rpy2 to use R in Python. Especially I want to use the MatchIt package but stuck on a detail. The call to the primary function of that package in R looks like this

# R code
m.out1 <- matchit(
    gruppe ~ geschlecht + alter + pflege,
    data = df,
    method = "nearest",
    distance = "glm"
)

The first argument is a "formula". I don't have an idea how to create such an object/argument in Python code? The other three arguments are no problem. The error from rpy2 is this:

[WARNING] R[write to console]: Error: 'formula' must be a formula object.

Traceback (most recent call last):
  ...
  File "...\AppData\Roaming\Python\Python39\site-packages\rpy2\rinterface.py", line 813, in __call__
    raise embedded.RRuntimeError(_rinterface._geterrmessage())
rpy2.rinterface_lib.embedded.RRuntimeError: Error: 'formula' must be a formula object.

This is the Python code producing that problem.

# Python code
import pandas
import rpy2
from rpy2.robjects.packages import importr
import rpy2.robjects as robjects
import rpy2.robjects.pandas2ri as pandas2ri

r_package_matchit = robjects.packages.importr('MatchIt')
func_matchit = robjects.r['matchit']

df = pandas.DataFrame({
    'gruppe': list('IICC'),
    'geschlecht': list('mwmw'),
    'alter': range(4),
    'pflege': range(4)
})

# convert the data frame from Pandas to R
with robjects.conversion.localconverter(
    robjects.default_converter + pandas2ri.converter):
    rdf = robjects.conversion.py2rpy(df)

func_matchit(formula='gruppe ~ geschlecht + alter + pflege',
             data=rdf, method='nearest',
             distance='glm')
1 Answers

Mutch easier then I thougt. rpy2 offers a Formula() for cases like this.

import rpy2
from rpy2.robjects import Formula
# ...
func_matchit(formula=Formula('gruppe ~ geschlecht + alter + pflege'),
             data=rdf, method='nearest',
             distance='glm')
Related