Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rpy2 (version 2.3.10) - importing data from R package into python

So I am trying to import some data from an R package into python in order to test some other python-rpy2 functions that I have written. In particular, I am using the SpatialEpi package in R and the pennLC dataset.

So I was able to import the rpy2 package and connect to the package correctly. However, I am not sure how to access the data in the package.

import rpy2.robjects as robjects
from rpy2.robjects.packages import importr
spep = importr("SpatialEpi")

However, I can't seem to access the data object pennLC in the SpatialEpi package to test the function. The equivalent R command would be:

data(pennLC)

Any suggestions.

like image 326
krishnab Avatar asked May 18 '26 14:05

krishnab


1 Answers

In R, doing data("foo") can create an arbitrary number of objects in the workspace. In rpy2 things are contained in an environment. This is making it cleaner.

from rpy2.robjects.packages import importr, data
spep = importr("SpatialEpi")
pennLC_data = data(spep).fetch('pennLC')

pennLC_data is an Environment (think of it as a namespace).

To list what was fetched:

pennLC_data.keys()

To get the data object wanted:

pennLC_data['pennLC'] # guessing here, it might be a different name
like image 129
lgautier Avatar answered May 20 '26 02:05

lgautier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!