13.6 Attributes
- Any vector can contain arbitrary additional metadata through its attributes.
- Can be thought as named list of vectors that can be attached to any object.
- We can get and set individual attribute values with
attr()or see them all at once withattributes().
x <- 1:10
attr(x, "greeting")
attr(x, "greeting") <- "Hi!"
attr(x, "farewell") <- "Bye!"
attributes(x)- Three very important attributes that used to implement fundamental parts of R:
- Names are used to name the elements of a vector.
- Dimensions (dims, for short) make a vector behave like a matrix or array.
- Class is used to implement the S3 object oriented system.
Note: We have learnt of the names, and we won’t discuss matrices in this discussion as matrices aren;t used in this book!
- Class controls how generic functions work.
- Generic functions are key to object programming since they make functions behave differently for different classes of input. The discussion of object programming is covered in details in Advanced R: http://adv-r.had.co.nz/OO-essentials.html#s3
- An example of generic function:
- The call to “UseMethod” means that this is a generic function, and it calls a specific method, a function, based on the class of the first argument.
Note: All methods are functions; not all functions are methods.
- To list all the methods for a generic, use
methods():
- For example, if
xis a character vector,as.Date()will callas.Date.character(); if it’s a factor, it’ll callas.Date.factor(). - We can see the specific implementation of a method with
getS3method():
- The most important S3 generic is
print()-> controls how the object is printed when we type its name at the console. - Subsetting functions:
[,[[and$are other important generics.