使用带生存库的 rpy2 从 python 调用 R 函数时出错

Error calling a R function from python using rpy2 with survival library

当使用 rpy2 接口从 python 中调用 R 生存包中的函数时,出现以下错误:

RRuntimeError: 公式错误[[2]] : 下标越界

有什么解决问题的建议吗?

谢谢

代码:

import pandas as pd
import rpy2.robjects.packages as rpackages
from rpy2.robjects.vectors import StrVector
from rpy2.robjects.packages import importr
import rpy2.robjects as ro
R = ro.r
from rpy2.robjects import pandas2ri

pandas2ri.activate()


## install the survival package
utils = rpackages.importr('utils')
utils.chooseCRANmirror(ind=1) # select the first mirror in the list
utils.install_packages(StrVector('survival'))


#Load the library and example data set
survival=importr('survival')
infert = R('infert')

## Linear model works fine
reslm=R.lm('case~spontaneous+induced',data=infert)

#Run the example clogit function, which fails
rescl=R.clogit('case~spontaneous+induced+strata(stratum)',data=infert)

经过尝试,我发现,无论您是否为 rpy2 的 R 实例提供要执行的完整 R 代码字符串,都是有区别的。

因此,您可以通过提供尽可能多的 R 代码来实现您的函数 运行:

#Run the example clogit function, which fails
rescl=R.clogit('case~spontaneous+induced+strata(stratum)',data=infert)

#But give the R code to be executed as one complete string - this works:
rescl=R('clogit(case ~ spontaneous + induced + strata(stratum), data = infert)')

如果您将return值捕获到R中的一个变量中,您可以检查数据并获取模型的关键信息 通过 R.

中的常用函数

例如

R('rescl.in.R <- clogit(case ~ spontaneous + induced + strata(stratum), data = infert)')

R('str(rescl.in.R)')

# or:
R('coef(rescl.in.R)')
## array([1.98587552, 1.40901163])

R('names(rescl.in.R)') 
## array(['coefficients', 'var', 'loglik', 'score', 'iter',
##        'linear.predictors', 'residuals', 'means', 'method', 'n', 'nevent',
##        'terms', 'assign', 'wald.test', 'y', 'formula', 'xlevels', 'call',
##        'userCall'], dtype='<U17')

它有很大帮助 - 至少在使用 rpy2 的第一阶段(对我来说也是如此),让你的 r 实例打开并并行尝试你所做的代码,因为输出在R 的可读性要好得多,您知道并看到自己在做什么以及可以解决什么问题。 在 Python 中,输出中的重要信息(如姓名等)被剥离 - 此外,它的打印也不漂亮。

在公式中包含 strata() 函数时失败,因为它没有在正确的环境中计算。在 R 中,公式是特殊的语言结构,因此需要由 rpy2 单独处理。

因此,对于您的示例,这看起来像:

rescl = R.clogit(ro.Formula('case ~ spontaneous + induced + strata(stratum)'),
                 data = infert)

有关详细信息,请参阅 rpy2.robjects.Formula 的文档。该文档还讨论了这种方法与@Gwang-jin-kim

提供的方法的优缺点