In R Subset filter rows in a data frame based on a condition in a column use in
The %in% operator in R is used to check if elements in a vector are present in another vector or a column of a data frame. It is often used to subset or filter rows in a data frame based on a condition in a specific column.
Here's an example of how to use %in% to subset a data frame based on a condition in a column:
# Create a data frame
df <- data.frame(
name = c("John", "Jane", "Tom", "Alice", "Bob"),
age = c(25, 30, 35, 40, 45),
city = c("New York", "London", "Paris", "Tokyo", "Sydney")
)
# Subset the data frame based on a condition in the "city" column
subset_df <- df[df$city %in% c("London", "Paris"), ]
# Print the subsetted data frame
print(subset_df)
Output:
name age city
2 Jane 30 London
3 Tom 35 Paris
In this example, we use %in% to check if the values in the "city" column (df$city) are present in the vector c("London", "Paris"). The resulting logical vector is then used to subset the data frame df, keeping only the rows where the condition is TRUE. The resulting subsetted data frame subset_df contains only the rows where the city is "London" or "Paris"
原文地址: http://www.cveoy.top/t/topic/h1jM 著作权归作者所有。请勿转载和采集!