How to Extract the First Element of a Nested List in R (Example Code)

This tutorial shows how to extract the top of each list element in a nested list in the R programming language.

Exemplifying Data

list_example <- list(list(1, 2),    # Creating example list
                list("a", "b"),
                list(10, 11))
list_example                        # Returning example list
# [[1]]
# [[1]][[1]]
# [1] 1
# 
# [[1]][[2]]
# [1] 2
# 
# 
# [[2]]
# [[2]][[1]]
# [1] "a"
# 
# [[2]][[2]]
# [1] "b"
# 
# 
# [[3]]
# [[3]][[1]]
# [1] 10
# 
# [[3]][[2]]
# [1] 11

Example: Selecting Top of Each Nested List with lapply Function

lapply(list_example, `[[`, 1)       # Apply lapply command
# [[1]]
# [1] 1
# 
# [[2]]
# [1] "a"
# 
# [[3]]
# [1] 10

Leave a Reply

Your email address will not be published. Required fields are marked *

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