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))'
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With