通过rpy2组合R和python:如何在python列表中读取R

时间:2017-01-11 15:36:00

标签: python r rpy2 fdr

我发现了类似的问题herehere,但我似乎无法弄清楚如何为自己的数据做这件事。

我在python中有一组浮动列表(实际上,每个列表大约有1000个浮点数); e.g。

[0.01,0.02,0.03,0.04,0.05]
[0.1,0.2,0.4,0.5,0.6,0.7]
[0.01,0.2,0.05,0.4]

对于每个列表,我想将python列表转换为R列表,在R列表上执行FDR测试以获取Q值列表,然后将Q值的R列表转换回python列表,然后继续我的剧本。

我的代码:

for each_list in SetOfLists:
    ro.r("library('devtools')") #load necessary package for task 
    ro.r("library('qvalue')")   #load necessary package for task
    pvals = ro.FloatVector(each_list)  #explain that each list is a set of floats 
    print ro.r("qobj <-qvalue(p=" + pvals + ")") #run the r function on each list
    #ro.r("qobj$lfdr") #get the FDR values from the R output                                                                                                                                                   
    #Then convert this list of FDR values back to python  

我对这一行有疑问:

print ro.r("qobj <-qvalue(p=" + pvals + ")")

例如,如果我创建该行:

  print ro.r("qobj <-qvalue(p=" + pvals + ")")

错误是:

> Traceback (most recent call last):   File "CalculateFDR.py", line 33,
> in <module>
>     print ro.r("qobj <-qvalue(p=" + pvals + ")") TypeError: cannot concatenate 'str' and 'FloatVector' objects

如果我将线稍微改为:

print ro.r("qobj <-qvalue(p= pvals)")

错误是:

  res = super(Function, self).__call__(*new_args, **new_kwargs)
Traceback (most recent call last):
  File "CalculateFDR.py", line 33, in <module>
    print ro.r("qobj <-qvalue(p=pvals)")
  File "/home/nis/aoife/env/local/lib/python2.7/site-packages/rpy2/robjects/__init__.py", line 321, in __call__
    res = self.eval(p)
  File "/home/nis/aoife/env/local/lib/python2.7/site-packages/rpy2/robjects/functions.py", line 178, in __call__
    return super(SignatureTranslatedFunction, self).__call__(*args, **kwargs)
  File "/home/nis/aoife/env/local/lib/python2.7/site-packages/rpy2/robjects/functions.py", line 106, in __call__
    res = super(Function, self).__call__(*new_args, **new_kwargs)
rpy2.rinterface.RRuntimeError: Error in qvalue(p = pvals) : object 'pvals' not found

我知道问题是我没有正确地将python列表转换为R列表,我不确定如何正确地执行此操作;因此,建议表示赞赏。

1 个答案:

答案 0 :(得分:0)

以防这对其他人有帮助,答案是:

devtools = importr("devtools")
qvalue = importr("qvalue")

for each_list in SetOfLists:
    pvals = ro.FloatVector(v)
    rcode = 'qobj <-qvalue(p=%s)' %(pvals.r_repr())
    res = ro.r(rcode)
    r_output1 = 'qobj$pvalue'
    r_output2 = 'qobj$qvalue'
    r_pvalue = ro.r(r_output1)
    r_qvalue = ro.r(r_output2)
    DictOfValues = dict(zip(r_pvalue,r_qvalue))

这是将python列表导入R的代码。