R Data Frame Subsetting: How to Filter Rows Using %in% Operator
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.\n\nHere's an example of how to use %in% to subset a data frame based on a condition in a column:\n\nR\n# Create a data frame\ndf <- data.frame(\n name = c("John", "Jane", "Tom", "Alice", "Bob"),\n age = c(25, 30, 35, 40, 45),\n city = c("New York", "London", "Paris", "Tokyo", "Sydney")\n)\n\n# Subset the data frame based on a condition in the "city" column\nsubset_df <- df[df$city %in% c("London", "Paris"), ]\n\n# Print the subsetted data frame\nprint(subset_df)\n\n\nOutput:\n\n name age city\n2 Jane 30 London\n3 Tom 35 Paris\n\n\nIn 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".
原文地址: https://www.cveoy.top/t/topic/pKne 著作权归作者所有。请勿转载和采集!