Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert python list of lists into R list of vectors in rpy2

Tags:

python

r

rpy2

I have a list of lists in python like the following like the following:

test = [[4, 2, 5, 3], [5, 2], [6, 3, 2, 5, 5]]

I want to input this into dunn.test in R using rpy2.

However, I am not sure how to convert this into a list of numeric vectors (R).

I am trying:

py2.robjects.ListVector(test)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3/dist-packages/rpy2/robjects/vectors.py", line 635, in __init__
    kv = [(str(k), conversion.py2ri(v)) for k,v in tlist]
  File "/usr/lib/python3/dist-packages/rpy2/robjects/vectors.py", line 635, in <listcomp>
    kv = [(str(k), conversion.py2ri(v)) for k,v in tlist]
ValueError: too many values to unpack (expected 2)

What is the correct way of doing this?

like image 901
Jack Arnestad Avatar asked Nov 07 '22 05:11

Jack Arnestad


1 Answers

See https://rpy2.github.io/doc/v2.9.x/html/vector.html#rpy2.robjects.vectors.ListVector

The constructor for ListVector can take a sequence of (name, value) pairs. Try:

rpy2.robjects.ListVector([(str(i), x) for i, x in enumerate(test)])

If no name, the way to do it at the robjects level is currently to first create an R list of defined length and then populate it:

res = rpy2.robjects.ListVector.from_length(3)
for i, x in enumerate(test):
    res[i] = rpy2.robjects.IntVector(x)
like image 140
lgautier Avatar answered Nov 14 '22 22:11

lgautier