Live code:

Live code
Lists
Published

March 10, 2023

Data

library(tidyverse)
library(vegan)
data(mite)
data(mite.env)
mite_dat <- mite.env %>%
  add_column(abundance = mite$LRUG)

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.

my_list <- list("stat", c(2,1,8))

This produces the following result:

my_list
[[1]]
[1] "stat"

[[2]]
[1] 2 1 8

That’s great! Lists behave similar to, but not exactly like, vectors. You can find the length of the vector:

length(my_list)
[1] 2

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:

my_list[2]
[[1]]
[1] 2 1 8

This output isn’t a vector; it’s still a list, so I cannot do math on it! The following code wouldn’t work:

2 * my_list[2]

Instead, to access each item in a list, we need to use double brackets, i.e. [[ ]]:

my_list[[2]]
[1] 2 1 8

Now we can work with the vector as normal

2 * my_list[[2]]
[1]  4  2 16

Storing items into lists will also require the double brackets. For example,

my_list[[3]] <- 5
my_list
[[1]]
[1] "stat"

[[2]]
[1] 2 1 8

[[3]]
[1] 5

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!

dat <- data.frame(x = 1:10, y = 11:20)
apply(dat, 2, mean)
   x    y 
 5.5 15.5