Working with Lists
A list is one of R’s most flexible data types.
Lists are similiar to vectors except that:
To create a list, use list():
## Make a list from scratch
buff_data <- list(id = "toni",
species = "buffalo",
age = 12,
sex = "female",
treatment = TRUE,
wt = 182,
tested = c(2013, 2014, 2016),
herd = c("west", "hilltop"))
class(buff_data)
buff_data## [1] "list"
## $id
## [1] "toni"
##
## $species
## [1] "buffalo"
##
## $age
## [1] 12
##
## $sex
## [1] "female"
##
## $treatment
## [1] TRUE
##
## $wt
## [1] 182
##
## $tested
## [1] 2013 2014 2016
##
## $herd
## [1] "west" "hilltop"
There are multiple ways you can get elements from a list:
1. By name with the $ operator:
buff_data$species
2. By name, in double square-brackets:
buff_data[['herd']]
3. By index number, in double square-brackets:
buff_data[[2]]
## [1] "toni"
## [1] "female"
## [1] 2013 2014 2016
If you’re not sure what the element names are, you can check with
names(). You can also reassign a name this way.
If a list element is a vector (or another list), you can keep adding square brackets:
$ and [[...]] return individual elements of
a list. Use single square brackets to return the
element(s) as another list object.
To change a list element, you simply give it a new value (just like a vector):
To add a list element, assign a new value to an element as if it was already there, and R will add it ‘on the fly’.
To delete a list element, set it to NULL.
## [1] "id" "species" "age" "gender" "treatment" "wt" "tested" "selected" "mother"
You can join two lists together with c():
more_meas <- list(diet_supplement = TRUE,
vaccinated = c(FALSE, FALSE, FALSE, TRUE))
c(buff_data, more_meas)## $id
## [1] "toni"
##
## $species
## [1] "buffalo"
##
## $age
## [1] 12
##
## $gender
## [1] "female"
##
## $treatment
## [1] TRUE
##
## $wt
## [1] 182
##
## $tested
## [1] 2013 2014 2016
##
## $selected
## [1] FALSE
##
## $mother
## [1] "luci"
##
## $diet_supplement
## [1] TRUE
##
## $vaccinated
## [1] FALSE FALSE FALSE TRUE
You can convert a list back to a vector with
unlist().
R will do its best to convert all the list elements to a common data type (probably character if they’re mixed), and returned a named vector.
## id species age gender treatment wt tested1 tested2 tested3 selected mother
## "toni" "buffalo" "12" "female" "TRUE" "182" "2013" "2014" "2016" "FALSE" "luci"
Lists are also referred to as ‘S3’ objects.
Data frames (including sf data frames) are also ‘S3’
(that’s why you can grab columns by name)
‘S4’ objects are newer - like ‘super lists’.
In addition to list elements, S4 objects can have named ‘slots’ that
you grab with the @ character.
Spatial data classes from the sp package are S4
objects.