How to Subset Lists in R (With Examples)


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.

Additional Resources

How to Convert a List to a Data Frame in R
How to Append Values to List in R

Leave a Reply

Your email address will not be published.