gpt4 book ai didi

python - 如何在 rpy2 中将列表传递给 R 并返回结果

转载 作者:行者123 更新时间:2023-12-02 21:24:50 24 4
gpt4 key购买 nike

我是第一次尝试使用 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

执行此操作的正确方法是什么?

最佳答案

我认为你不能直接将 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')]

引用:

关于python - 如何在 rpy2 中将列表传递给 R 并返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25269655/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com