How to pass a list to R in rpy2 and get result back

試著忘記壹切 提交于 2021-01-05 12:27:50

问题


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]

I want to do call in R

ks.test(l, pexp)

How can I do that?

My initial try is

#!/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)

This clearly isn't the right way to do it as I get

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?


回答1:


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')]

Reference:

  • Working with R’s OOPs
  • Functions
  • Vectors and arrays


来源:https://stackoverflow.com/questions/25269655/how-to-pass-a-list-to-r-in-rpy2-and-get-result-back

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!