在Python中使用R计算p值

0 投票
2 回答
1121 浏览
提问于 2025-04-18 05:36

我想在Python中使用R来计算p值。我正在使用一个叫做rpy2的包。我实时生成count_a和count_b,并同时计算p值。

当我运行我的脚本时,Python意外关闭,并出现了这个错误信息:

“错误:'rho'必须是一个环境,而不是NULL:在C级评估中检测到

启动时 - 警告信息:

中止陷阱:6”

以下是我的数据:

 count_a  count_b

 94       107
 109      92
 90       89
 18       13

下面是我的代码:

import rpy2.robjects as R
out= open(args.outfile, 'w')
binom=R.r['binom.test'](c(count_a,count_b))
P_val=binom['p.value'][0][0]
out.write(str(count_a) + '\t' + str(count_b) + '\t' + str(P_val)
out.close()

有没有什么建议,或者在Python中计算一对值的p值的选项?

binom对象已计算:

Exact binomial test

数据:c(94L, 107L)
成功次数 = 94,试验次数 = 201,p值 = 0.3974
替代假设:成功的真实概率不等于0.5
95%置信区间:
0.3971286 0.5391627
样本估计:
成功的概率
0.4676617

然而,在提取p值时,我遇到了这个错误:

文件“/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/rpy2/robjects/vectors.py”,第233行,在getitem
res = super(Vector, self).getitem(i)
类型错误:'str'对象不能被解释为索引

2 个回答

1

这个讨论串来看,早期版本的rpy2和R 3.0.2之间可能有问题。看起来,对于R 3.0.2,推荐使用的rpy2版本至少是rpy2-2.3.8。

0
The problem was binom.names is a  StrVector, and does not support index, however it can be     converted to a Python list easily enough,and then extract those values.

    my_vec = R.IntVector([count_a,count_b])
    binom=R.r['binom.test'](my_vec)
    names= binom.names
    names = list(names)
    P_val= binom[names.index('p.value')][0]

想要了解更多,可以访问这个博客 http://telliott99.blogspot.com/2010/11/rpy-r-from-python-2.html

撰写回答