To filter elements of a list based on a condition in R, you can use the subset function or logical indexing.
In this example,
numbers
with integer values.numbers <- c(1, 2, 3, 4, 5)
threshold <- 3
filtered_numbers <- numbers[numbers > threshold]
print(filtered_numbers)
[1] 4 5
In this example,
words
with string values.grepl
function to create a logical vector indicating if a substring is present in each element.words <- c('apple', 'banana', 'cherry', 'date', 'elderberry')
substring <- 'erry'
filtered_words <- words[grepl(substring, words)]
print(filtered_words)
[1] "cherry" "elderberry"
In this tutorial, we learned How to Filter Elements of a List based on a Condition in R language with well detailed examples.