Читать книгу The Big R-Book - Philippe J. S. De Brouwer - Страница 203
Note – Compare addressing slots in S4 and S3
ОглавлениеIn order to access slots of an S4 object, we use @
, not $
:
There is also a specific function to get attributes froman object: attr()
. This function allows to create attributes, change them or even remove them (by setting them to NULL)
attr()
# This will do the same as my_cust_bank@phone: attr(my_cust_bank, ‘phone’) ## [1] 987654321 # The function also allows partial matching: attr(my_cust_bank, which=’ph’, exact = FALSE) ## [1] 987654321 # attr can also change the value of an attribute. attr(my_cust_bank, which=’phone’) <- ‘123123123’ # Let us verify: my_cust_bank@phone ## [1] “123123123” # It is even possible to create a new attribute or remove one. attr(my_cust_bank, ‘something’) <- ‘Philippe’ attr(my_cust_bank, ‘something’) ## [1] “Philippe” attr(my_cust_bank, ‘something’) <- NULL attr(my_cust_bank, ‘something’) ## NULL str(my_cust_bank) # the something attribute is totally gone ## Formal class ‘Bnk’ [package “.GlobalEnv”] with 2 slots ## ..@ name : chr “HSBC” ## ..@ phone: chr “123123123”