使用 rpy2 从 Python 调用 R 函数

Calling R functions from Python using rpy2

我一直在遵循 rpy2 文档中有关使用 R 的 OOPS 的说明:https://rpy2.readthedocs.io/en/version_2.8.x/robjects_oop.html。我正在尝试创建一个 Python class 来调用 R 包 randomForestSRC 中的函数 rfsrc。

这在什么条件下有效? rpy2 是否有允许您访问的固定包列表,如果有,randomForestSRC 是否在该列表中?

当我从 Jupyter Notebook (Python 3, R 3.5.1) 中 运行 下面的代码时,我得到了错误: Error in (function (f, signature = character() , 其中 = topenv(parent.frame()), : 没有找到 'rfsrc'

的通用函数
import rpy2.robjects.packages as rpackages
from rpy2.robjects.vectors import StrVector

utils = rpackages.importr('utils')
utils.chooseCRANmirror(ind=1) # select the first mirror in the list
packnames = ('randomForestSRC', 'survival', 'tidyverse', 'magrittr', 'ggRandomForests', 'mlr')
utils.install_packages(StrVector(packnames))

from rpy2.robjects.packages import importr
randomForestSRC = importr('randomForestSRC')
from rpy2.robjects.methods import RS4Auto_Type
import six

class rfsrc(six.with_metaclass(RS4Auto_Type)):
    __rname__ = 'rfsrc'
    __rpackagename__ = 'randomForestSRC'

我还需要做什么才能让它工作?

我也尝试了如下所示的手动方法,得到了同样的错误。

import rpy2.robjects as robjects
import rpy2.rinterface as rinterface
from rpy2.robjects.packages import importr

lme4 = importr("randomForestSRC")
getmethod = robjects.baseenv.get("getMethod")

StrVector = robjects.StrVector

class rfsrc(robjects.methods.RS4):

    _coef = getmethod("rfsrc", 
                  signature = StrVector(["rfsrc", ]),
                  where = "package:randomForestSRC")

    def _call_get(self):
        return self.do_slot("call")
    def _call_set(self, value):
        return self.do_slot("call", value)
    call = property(_call_get, _call_set, None, "Get or set the RS4 slot      'call'.")

    def coef(self):
        """ fitted coefficients """
        return self._coef(self)

有几个问题。我选了一个可能是所有其他人的起源。

Does rpy2 have a fixed list of packages that it allows you to access and if so is randomForestSRC on this list?

rpy2 只能使用 R 安装可用的 R 包。该文档有一些关于从 Python 安装 R 包的内容(另外,请注意 rpy2-2.9.x 文档的 URL):https://rpy2.github.io/doc/v2.9.x/html/robjects_rpackages.html#installing-removing-r-packages

编辑:

问题已编辑,现在集中在错误消息 no generic function found for 'rfsrc' 上。错误来自 R,因为没有找到名为 "rfsrc" 的通用函数。

我认为 rfsrc 只是一个常规的 R 函数(不是泛型,请参阅 https://github.com/cran/randomForestSRC/blob/master/R/rfsrc.R )。另外,我不是包 randomForest 大量使用 S4,您尝试使用的 rpy2 功能是专门为 R 的 S4 OOP 系统设计的。