使用R计算python中的p值

时间:2014-05-06 21:18:25

标签: python r statistics rpy2 p-value

我想用R.计算python中的p值。我正在使用这个包rpy2.我正在生成count_a和count_b,并计算p值。  当我运行我的脚本时,python意外关闭,并收到此错误消息:

"错误:' rho'必须是非NULL的环境:在C级eval中检测到 在启动期间 - 警告消息:

中止陷阱: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值的任何建议或选项?

计算二进制对象:

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(矢量,自我)。 getitem (i) TypeError:' str'对象不能被解释为索引

2 个答案:

答案 0 :(得分:1)

this thread看来早期版本的rpy2和R 3.0.2可能存在问题。看起来R 3.0.2的推荐版本至少是rpy2-2.3.8。

答案 1 :(得分: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