Simd
Simd

Reputation: 21333

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

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?

Upvotes: 2

Views: 2893

Answers (1)

longhua
longhua

Reputation: 4252

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:

Upvotes: 6

Related Questions