如何在 rpy2 中将列表传递给 R 并返回结果 [英] How to pass a list to R in rpy2 and get result back
本文介绍了如何在 rpy2 中将列表传递给 R 并返回结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我第一次尝试使用 rpy2.假设我在 python 中有一个列表
I am trying to use rpy2 for the first time. Let's say I have in python a list
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
这样做的正确方法是什么?
What is the right way to do this?
推荐答案
我认为您不能直接将 Python 列表传递给 R.您可以在使用之前转换为 R int 向量.
I don't think you can pass a python list to R directly. You can convert to a R int vector before use it.
#!/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')]
参考:
这篇关于如何在 rpy2 中将列表传递给 R 并返回结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文