To remove elements from a vector based on a condition in R, you can use indexing or the `subset` function.
In this example,
numbers
with some elements.numbers <- c(1, 2, 3, 4, 5)
threshold <- 3
modified_numbers <- numbers[numbers <= threshold]
print(paste('Modified vector after removing elements greater than', threshold, ':', modified_numbers))
[1] "Modified vector after removing elements greater than 3 : 1 2 3"
In this example,
names
with some elements.is_long_name
that returns TRUE
if the length of the string is greater than a specified value.subset
function to subset the vector based on the predicate condition.names <- c('John', 'Alice', 'Michael', 'Emma')
max_length <- 5
is_long_name <- function(name) {
nchar(name) > max_length
}
modified_names <- subset(names, !sapply(names, is_long_name))
print(paste('Modified vector after removing long names:', modified_names))
[1] "Modified vector after removing long names: John Alice Emma"
In this tutorial, we learned How to Remove Element from List based on a Condition in R language with well detailed examples.