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

时间:2018-05-16 11:47:46

标签: python r rpy2 survival-analysis

当使用rpy2接口在python中调用R中的survival包中的函数时,我收到以下错误:

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)

2 个答案:

答案 0 :(得分:3)

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

因此,您可以通过尽可能多地使用R代码来运行您的函数:

RegExp

如果将返回值捕获到R中的变量,则可以检查数据并获取模型的关键信息 通过R的常规功能。

E.g。

#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)')

它有很多帮助 - 至少在第一阶段使用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') (对我来说也是如此),让你的r实例打开并尝试并行执行代码,因为R中的输出是更具可读性,您知道并了解自己在做什么以及可以解决的问题。 在Python中,输出被删除了重要的信息(比如名称等) - 此外,它还没有很好的打印。

答案 1 :(得分:0)

在公式中包含strata()函数时,此方法将失败,因为未在正确的环境中对其进行评估。在R中,公式是特殊的语言构造,因此需要分别由rpy2处理。

因此,以您的示例为例,

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

有关更多详细信息,请参见rpy2.robjects.Formula的文档。该文档还讨论了这种方法与@ Gwang-jin-kim提供的方法的优缺点