Table of Contents
Subsetting lists in R is a way to extract specific elements from a list object. This can be done by using the ‘[]’ operator or the ‘$’ operator. For example, a list could be subsetted by indexing with ‘[ ]’ operator and providing the index numbers of the elements to be extracted or by using the ‘$’ operator and providing the name of the element to be extracted. This can be used to extract or modify specific elements from a list, which can be used in further data manipulation.
You can use the following syntax to subset lists in R:
#extract first list item my_list[[1]] #extract first and third list item my_list[c(1, 3)] #extract third element from the first item my_list[[c(1, 3)]]
The following examples show how to this syntax with the following list:
#create list my_list <- list(a = 1:3, b = 7, c = "hey") #view list my_list $a [1] 1 2 3 $b [1] 7 $c [1] "hey"
Example 1: Extract One List Item
The following code shows various ways to extract one list item:
#extract first list item using index value my_list[[1]] [1] 1 2 3 #extract first list item using name my_list[["a"]] [1] 1 2 3 #extract first list item using name with $ operator my_list$a [1] 1 2 3
Notice that all three methods lead to the same result.
Example 2: Extract Multiple List Items
The following code shows various ways to extract multiple list items:
#extract first and third list item using index values my_list[c(1, 3)] $a [1] 1 2 3 $c [1] "hey" #extract first and third list item using names my_list[c("a", "c")] $a [1] 1 2 3 $c [1] "hey"
Both methods lead to the same result.
Example 3: Extract Specific Element from List Item
The following code shows various ways to extract a specific element from a list item:
#extract third element from the first item using index values my_list[[c(1, 3)]] [1] 3 #extract third element from the first item using double brackets my_list[[1]][[3]] [1] 3
Both methods lead to the same result.