python - 当数据通过 rpy2 传递时,lmtest/lrtest 抛出 data.frame 错误

标签 python r rpy2

仅当我通过 rpy2 从用户定义的函数调用 lrtest(来自 lmtest 包)时,才会出现错误。

R:

continuous.test <- function(dat) {
  require('lmtest')
  options(warn=-1)
  model <- lm(formula='pheno ~ .', data=dat)
  anova <- lrtest(model,'interaction')
  pval  <- anova$"Pr(>Chisq)"[2]
}

当我从 R 解释器调用此函数时,一切都运行正常。但是,从以下 python 代码片段调用时收到错误。请注意,这个特定的 python 文件成功地对 rpy2 进行了许多其他调用。

Python:

...
kway_dat = R.DataFrame(dataframe) # this is a valid dataframe, it's used in other calls.
...
R.r("source('/path/to/user/defined/file/perm_test.r')")
continuous_test = R.r['continuous.test']
pval = continuous_test(kway_dat)

错误:

Error in is.data.frame(data) : object 'dat' not found
Traceback (most recent call last):
  File "./test_r_.py", line 83, in <module>
    pval = continuous_test(kway_dat)
  File "/usr/lib/python2.6/site-packages/rpy2-2.2.6dev_20120806-py2.6-linux-x86_64.egg/rpy2/robjects/functions.py", line 82, in __call__
    return super(SignatureTranslatedFunction, self).__call__(*args, **kwargs)
  File "/usr/lib/python2.6/site-packages/rpy2-2.2.6dev_20120806-py2.6-linux-x86_64.egg/rpy2/robjects/functions.py", line 34, in __call__
    res = super(Function, self).__call__(*new_args, **new_kwargs)
rpy2.rinterface.RRuntimeError: Error in is.data.frame(data) : object 'dat' not found

疑难解答:

  • 我已经在 R 中测试了代码,一切正常。
  • 我已通过 rpy2 将数据帧从 python 传递到 R,并从 R 函数调用 is.data.frame(dat),它返回 true,因此问题出在 lmtest 或 lrtest + rpy2 上。

任何帮助都会很棒。谢谢大家!

最佳答案

提供一个独立的示例会更容易(这样人们就可以准确地重现您所经历的情况)。

仍然是一个可能的答案:您可能想检查文件的内容 /path/to/user/define/file/perm_test.r 确实如您所想。

我还为一个独立的示例添加了一个 stub :

r_code = """
  require('lmtest')
  options(warn=-1)
  continuous.test <- function(dat) {
    model <- lm(formula='pheno ~ .', data=dat)
    anova <- lmtest::lrtest(model,'interaction')
    pval  <- anova$"Pr(>Chisq)"[2]
  }
"""

from rpy2.robjects import packages
my_r_pack = packages.SignatureTranslatedAnonymousPackage(r_code, "my_r_pack")

# [build a demo kway_dat here]

my_r_pack.continuous_test(kway_dat)

关于python - 当数据通过 rpy2 传递时,lmtest/lrtest 抛出 data.frame 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12550718/

相关文章:

python - 安装并使用 RPy2(使用 conda),以便它使用/usr/lib/R R 中的默认 R 安装

Python - 双条件 data.loc

python - virtualenvwrapper 中的环境和项目是什么关系?

python - 需要超过 0 个值才能解压

删除包含值的行之后的所有行

javascript - R Shiny : Getting information from Datatable with JS in shiny

python - 特拉维斯 CI : error when installing rpy2

python - Heroku 部署 - PermissionError : [Errno 13] Permission denied: '/etc/passwd-'

sql - 删除 R 或 SQL 中最不完整的重复行

python - 终生无法安装 rpy2 - gcc 错误