Search code examples
pythonrpy2

How to set an attribute to a vector in rpy2


How to add attributes to vectors in python with rpy2. As an example how can I reproduce this R code:

library(evir)
pot<-c(2.0,3.2,4,5,6,7)
ts<-c(1,6,7,19,20,30)
attr(pot,"times")<-ts
output<-decluster(pot,run=2)

I can't find any help after searching several hours on the net. I guess Laurent has the answer ;-)


Solution

  • Use the attribute slots. What is described about it in the doc for S4 objects applies to attributes (http://rpy2.readthedocs.org/en/version_2.7.x/notebooks/s4class.html).

    Here it should work with:

    from rpy2.robjects.vectors import FloatVector, IntVector
    pot = FloatVector((2.0, 3.2, 4, 5, 6, 7))
    ts = IntVector((1,6,7,19,20,30))
    pot.slots['times'] = ts
    

    For rpy2 < 2.7, you should use do_slot_assign :

    pot.do_slot_assign("times",ts)