简体   繁体   中英

How to combine slots of S4 class object in one vector

I created an S4 class with two slots for example

setClass("A", 
     slots = c(
         x = "numeric",
         y = "numeric"
     )
)

and created some objects

 l1<-new("A", x = 5, y = 8)
 l2<-new("A", x = 6, y = 7)
 l3<-new("A", x = 7, y = 6)
 l4<-new("A", x = 8, y = 5)

Now I want to combine slot x into one vector. I do it like

c<-c(l1@x,l2@x,l3@x,l4@x)

Is there any better way of doing this, preferably loop because no of objects is not fix.

This becomes much easier to do if your 4 objects are contained in a list:

my.list <- list(l1, l2, l3, l4)

sapply(my.list, attr, 'x')

[1] 5 6 7 8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM