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

[亡魂溺海] 提交于 2019-12-10 17:59:50

问题


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.


回答1:


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



回答2:


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])


来源:https://stackoverflow.com/questions/23326651/rpy2-version-2-3-10-importing-data-from-r-package-into-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!