To filter items of a vector based on a condition in R, you can use the subset function or logical indexing.
In this example,
# Define a vector containing elements
vector <- c(1, 5, 10, 15, 20)
# Specify the threshold for filtering
threshold <- 10
# Use subset function to filter items greater than the threshold
filtered_vector <- subset(vector, vector > threshold)
# Print the filtered vector
print(filtered_vector)
[15, 20]
In this example,
# Define a vector containing elements
vector <- c(1, 5, 10, 15, 20)
# Specify the condition for filtering
condition <- vector %% 2 == 0 # Select even numbers
# Use logical indexing to filter items meeting the condition
filtered_vector <- vector[condition]
# Print the filtered vector
print(filtered_vector)
[10, 20]
In this tutorial, we learned How to Filter Items of a Vector based on a Condition in R language with well detailed examples.