R Named Lists
Named Lists
In the Lists chapter, you got the items by their position: thislist[1], thislist[2], and so on.
That works for short lists, but in a longer list it is hard to remember which position holds which value. Instead, you can give each item a name, like the fields on a contact card:
Example
person <- list(name = "John", age = 40, married = TRUE)
person
Try it Yourself »
R prints the name of each item with a $ sign in front of it.
Get an Item by Name
Use the $ sign, or double brackets [[ ]] with the name in quotes, to get the value of an item:
Example
person <- list(name = "John", age = 40, married = TRUE)
person$name
person[["age"]]
Try it Yourself »
Note: This is the same $ sign that you use to get a column from a data frame. A data frame is a list of columns, where each column has a name.
[ ] or [[ ]]?
Single brackets [ ] return a smaller list. Double brackets [[ ]] return the value itself:
Example
person <- list(name = "John", age = 40, married = TRUE)
class(person["name"])
class(person[["name"]])
Try it Yourself »
Think of the list as a train with wagons: [ ] gives you a wagon, and [[ ]] gives you what is inside the wagon.
Change, Add and Remove Items
Use the $ sign to change an item, or to add a new one. To remove an item, set it to NULL:
Example
person <- list(name = "John", age = 40, married = TRUE)
person$age <- 41
person$job <- "Teacher"
person$married <- NULL
person
Try it Yourself »
Get the Names
The names() function returns the names of all the items:
Example
person <- list(name = "John", age = 40, married = TRUE)
names(person)
Try it Yourself »
You can use it to loop through the list, and print both the name and the value of each item:
Example
person <- list(name = "John", age = 40, married = TRUE)
for (key in names(person)) {
print(paste(key, ":", person[[key]]))
}
Try it Yourself »