如何将列表传递给rpy2中的R并获取结果

时间:2014-08-12 16:40:26

标签: python r rpy2

我第一次尝试使用rpy2。假设我在python中有一个列表

l = [1,2,3,4,5,6]

我想在R中打电话

ks.test(l, pexp)

我该怎么做?

我最初的尝试是

#!/usr/bin/python
import rpy2.robjects as robjects

l = [1,2,3,4,5]

f = robjects.r('''
f<-function(l){
    ks.test(l, pexp)
}''')
print f(l)

这显然不是我得到的正确方法

Error in sort.int(x, na.last = na.last, decreasing = decreasing, ...) : 
  'x' must be atomic
Traceback (most recent call last):
  File "./rpy2-test.py", line 12, in <module>
    print f(l)
  File "/usr/local/lib/python2.7/dist-packages/rpy2/robjects/functions.py", line 166, in __call__
    return super(SignatureTranslatedFunction, self).__call__(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/rpy2/robjects/functions.py", line 99, in __call__
    res = super(Function, self).__call__(*new_args, **new_kwargs)
rpy2.rinterface.RRuntimeError: Error in sort.int(x, na.last = na.last, decreasing = decreasing, ...) : 
  'x' must be atomic

这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

我认为你不能直接将一个python列表传递给R.您可以在使用之前转换为R int向量。

#!/usr/bin/python
import rpy2.robjects as robjects

l = [1,2,3,4,5]

# get ks.test via execute string as R statement
test = robjects.r('ks.test')
# get a built-in functions variables directly
pexp = robjects.r.pexp

l_vector = robjects.IntVector(l)
result = test(l_vector, pexp)
print result[result.names.index('p.value')]

参考: