How to Extract Element of List in R (2 Examples)

In this post you’ll learn how to extract a list element based on an index in R programming.

Creation of Example Data

example_list <- list(data.frame(x = "XXX",    # Constructing example list
                                y = 10:15,
                                z = LETTERS[10:15]),
                     1:7,
                     7:1)
example_list                                  # Showing list in RStudio console
# [[1]]
#     x  y z
# 1 XXX 10 J
# 2 XXX 11 K
# 3 XXX 12 L
# 4 XXX 13 M
# 5 XXX 14 N
# 6 XXX 15 O
# 
# [[2]]
# [1] 1 2 3 4 5 6 7
# 
# [[3]]
# [1] 7 6 5 4 3 2 1
#

Example 1: Extracting Entire List Element from List Using [[]]

example_list[[2]]                             # Entire list element
# [1] 1 2 3 4 5 6 7

Example 2: Extracting Sub-Element of Data Frame in List

example_list[[1]][ , "z"]                     # Data frame element
# [1] "J" "K" "L" "M" "N" "O"

Related Tutorials & Further Resources

Please find some related R programming tutorials on topics such as loops, extracting data, and lists in the list below.

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top