Lists in R are ordered collections of data that can be of different classes.
Creating Lists
Action
Syntax
New list (empty)
listname <- list()
New list (misc)
listname <- list(1L, "abc", 10.3)
Accessing List Elements
Action
Syntax
Access an element
list[position]
Change a value
list[position] <- newvalue
See number of values in a list
length(list)
See if item is present in a list
item %in% list
Adding and Removing List Elements
Action
Syntax
Add item to a list
append(list)
Add item to a list at a specific position
append(list, after=index number)
Remove item from list
newlist <- list[-index number]
Inputs:
#Create list
mylist <- list("apple", "peach", "plum")
#Access the second element of a list
mylist[2]
#Change the value of the first element of a list
mylist[1] <- "banana"
mylist
#See the number of values in a list
length(mylist)
#Check if item exists in list
"plum" %in% mylist
#Add an item to the list
append(mylist, "orange", after=2)
mylist
#Remove an item at index=3 from a list
mylist <- list("apple", "peach", "plum")
newlist <- mylist[-3]
newlist
Outputs:
#Access the second element of a list
"peach"
#Change the value of the first element of a list
[[1]]
[1] "banana"
[[2]]
[1] "peach"
[[3]]
[1] "plum"
#See the number of values in a list
3
#Check if item exists in list
TRUE
#Add an item to the list
[[1]]
[1] "banana"
[[2]]
[1] "peach"
[[3]]
[1] "orange"
[[4]]
[1] "plum"
#Remove an item from a list
[[1]]
[1] "apple"
[[2]]
[1] "peach"