How to access the internal functions of an R package using rpy2?

Viewed 310

I am working with the GMCM package of R in Python using rpy2. There are a few internal functions of GMCM package which can be accessed only using the ::: operator. For example the function qgmm.marginal cannot be accessed using rpy2 in the usual way.

Here is my Python code:

import rpy2

import rpy2.robjects as robjects
from rpy2.robjects.packages import importr  
gmcm_r = importr('GMCM')
data_r = gmcm_r.SimulateGMCMData(n = 100, m =3, d=2)

print(gmcm_r.Uhat(data_r.rx2('z'))) # works
print(gmcm_r.qgmm.marginal(gmcm_r.Uhat(data_r.rx2('z')))) # does not work
# AttributeError: module 'GMCM' has no attribute 'qgmm'

The corresponding R code is

library(GMCM)
data = SimulateGMCMData(n = 100, m =3, d=2)
u = Uhat(data$z) #works
GMCM:::qgmm.marginal(u, theta)#works

How do we access these internal functions using rpy2?

1 Answers

You had two mistakes:

  1. You retained an R syntax dot (.) that you should have converted to a python syntax underscore (_). That's what caused the error you observed.
  2. Once you fix that error, though, you'd find a new one: You didn't specify the theta argument to the function you're trying to call.

Here's a working solution:

import rpy2

import rpy2.robjects as robjects
from rpy2.robjects.packages import importr  
gmcm_r = importr('GMCM')
data_r = gmcm_r.SimulateGMCMData(n = 100, m =3, d=2)

print(gmcm_r.Uhat(data_r.rx2('z'))) # works
## [Output omitted]

u = gmcm_r.Uhat(data_r.rx2('z'))
theta = data_r.rx2('theta') ## Need to specify theta
# print(gmcm_r.qgmm.marginal(u, theta)) ## Need to change the dot after qgmm
print(gmcm_r.qgmm_marginal(u, theta))   ## to an underscore

             [,1]        [,2]
  [1,]   8.660195  0.26664200
  [2,]   7.626162  7.86828143
  [3,]   7.862762  8.75474254
## [output truncated]
Related