Find List Elements Containing Particular Values in R (Example Code)
In this tutorial, I’ll demonstrate how to find and extract all list elements that contain a specific values in the R programming language.
Creation of Example Data
x <- list(1:6, # Create example list "XXX", 3) x # Print example list # [[1]] # [1] 1 2 3 4 5 6 # # [[2]] # [1] "XXX" # # [[3]] # [1] 3 |
x <- list(1:6, # Create example list "XXX", 3) x # Print example list # [[1]] # [1] 1 2 3 4 5 6 # # [[2]] # [1] "XXX" # # [[3]] # [1] 3
Example: Find List Elements that Contain Certain Value
sapply(x, function(y) 3 %in% y) # Index positions of matches # [1] TRUE FALSE TRUE |
sapply(x, function(y) 3 %in% y) # Index positions of matches # [1] TRUE FALSE TRUE