Live code:
Data
Lists
Lists are simply another data object in R. List can hold elements of different types, such as vectors, strings, and numbers, and even more lists! We create a list using the list()
function.
This produces the following result:
That’s great! Lists behave similar to, but not exactly like, vectors. You can find the length of the vector:
Also, it would be extremely useful to be able to access each element of my_list
. However, if we were to use the usual [ ]
notation to index, notice what happens:
This output isn’t a vector; it’s still a list, so I cannot do math on it! The following code wouldn’t work:
Instead, to access each item in a list, we need to use double brackets, i.e. [[ ]]
:
Now we can work with the vector as normal
Storing items into lists will also require the double brackets. For example,
Why are we working with lists? We’ll need them for k-fold CV!
apply()
A useful function is the apply()
function, which applies the same function to either ALL the rows or ALL the columns. It takes three arguments: what R object you want to apply the function two, by row (1) or by column (2), and the function itself.
In the following code, I am applying the mean function to each column of dat
. Notice that I get back a vector of column means!