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 |
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 |
lapply(list_example, `[[`, 1) # Apply lapply command # [[1]] # [1] 1 # # [[2]] # [1] "a" # # [[3]] # [1] 10