Вопрос

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.

Это было полезно?

Решение

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

Другие советы

So I figured out an answer based upon some guidance from Laurent's message above.

I am using rpy2 version 2.3.10, so that introduces some differences from Laurent's code above. Here is what I did.

import rpy2.objects as robj
from rpy2.robjects.packages import importr
spep = importr('SpatialEpi', data = True)
data = spep.__rdata__.fetch('pennLC')

First note that there is no .data method in rpy2 2.3.10--the name might have changed. But instead, the 2.3.10 documentation indicates that using the data=True argument in the importr will place an PackageData object under .Package.__rdata__ . So I can do afetchon therdata` object.

Then when I want to access the data, I can use the following code.

data['pennLC'][1]

In [43]: type(d['pennLC'][1])
Out[43]: rpy2.robjects.vectors.DataFrame

To view the data:

print(data['pennLC'][1])
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top