Attributes
You have made it to the last exercise in the course! Congrats! Let's finish up with an easy one.
Attributes are a bit of extra metadata about your data structure. Some of the most common attributes are: row names and column names, dimensions, and class. You can use the attributes()
function to return a list of attributes about the object you pass in. To access a specific attribute, you can use the attr()
function.
Exploring the attributes of cash
:
attributes(cash)
$names
[1] "company" "cash_flow" "year"
$row.names
[1] 1 2 3 4 5 6 7
$class
[1] "data.frame"
attr(cash, which = "names")
[1] "company" "cash_flow" "year"
This is a part of the course
“Introduction to R for Finance”
Exercise instructions
- The matrix
my_matrix
and the factormy_factor
are defined for you. - Use
attributes()
onmy_matrix
. - Use
attr()
onmy_matrix
to return the"dim"
attribute. - Use
attributes()
onmy_factor
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# my_matrix and my_factor
my_matrix <- matrix(c(1,2,3,4,5,6), nrow = 2, ncol = 3)
rownames(my_matrix) <- c("Row1", "Row2")
colnames(my_matrix) <- c("Col1", "Col2", "Col3")
my_factor <- factor(c("A", "A", "B"), ordered = T, levels = c("A", "B"))
# attributes of my_matrix
# Just the dim attribute of my_matrix
# attributes of my_factor