How to Subset List Elements Conditionally in R (Example Code)
This page explains how to extract certain list elements based on a logical condition in the R programming language.
Creation of Example Data
example_list <- list(l1 = 10:3, # Constructing example list l2 = letters[15:20], l3 = 9:7) example_list # Displaying example list in RStudio console # $l1 # [1] 10 9 8 7 6 5 4 3 # # $l2 # [1] "o" "p" "q" "r" "s" "t" # # $l3 # [1] 9 8 7 |
example_list <- list(l1 = 10:3, # Constructing example list l2 = letters[15:20], l3 = 9:7) example_list # Displaying example list in RStudio console # $l1 # [1] 10 9 8 7 6 5 4 3 # # $l2 # [1] "o" "p" "q" "r" "s" "t" # # $l3 # [1] 9 8 7
Example: Apply Filter() Function to Select List Elements Conditionally
Filter(function(x) length(x) > 5, example_list) # Using Filter() function # $l1 # [1] 10 9 8 7 6 5 4 3 # # $l2 # [1] "o" "p" "q" "r" "s" "t" |
Filter(function(x) length(x) > 5, example_list) # Using Filter() function # $l1 # [1] 10 9 8 7 6 5 4 3 # # $l2 # [1] "o" "p" "q" "r" "s" "t"