Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an element (vector) to a list in rpy2

In R, I can add elements to a list easily:

mylist = list()
mylist[[1]] = c(1,2)
mylist[[2]] = c(2,3)
mylist[[length(mylist)+1]] = c(3,4)

How do I do this in rpy2? I am using rpy2 2.1.9. I tried the following but it doesn't work

import rpy2.robjects as robjects
a = robjects.r('list()')
b = robjects.IntVector([1,2])
a[0] = b
IndexError: Index out of range.
a[1] = b
IndexError: Index out of range.
aa = a.__add__(b) # But this makes a list out of the vector
aa.r_repr()
'list(1L, 2L)'
# We wanted something like the following instead:
aaa = robjects.r('list(c(1,2))')
aaa.r_repr()
'list(c(1, 2))'
like image 614
highBandWidth Avatar asked Feb 22 '11 23:02

highBandWidth


2 Answers

If you want to use R's "[[<-" operator, you'll have to call the method rx2() (see [assigning, R-style][1]).

In rpy2-2.2.0dev, you can do a.rx2[1] = b.

[1]: http://rpy.sourceforge.net/rpy2/doc-2.2/html/vector.html#assigning-r-style assigning, R-style

like image 199
lgautier Avatar answered Oct 22 '22 14:10

lgautier


I'm not sure that you can do this with the current version of rpy2, but you can try out the rpy2.rlike.container.TaggedList class, which can act as an R list and supports appending, removing and retagging items. As far as I can tell, there must be a bug in the assignment for lists and vectors.

like image 41
Noah Avatar answered Oct 22 '22 13:10

Noah