如何用dplyr基于某行值删除多行数据
Using dplyr to Remove Pets That Have Ever Bitten
First, let's recreate your sample dataset so we're working with the same starting point:
library(dplyr) # Original dataset pet_data <- tibble( Pet = c("Cow", "Cow", "Cow", "Dog", "Dog", "Dog", "Tiger", "Tiger", "Tiger"), Day = c("Monday", "Tuesday", "Wednesday", "Monday", "Tuesday", "Wednesday", "Monday", "Tuesday", "Wednesday"), Bite = c("No", "No", "No", "No", "No", "No", "No", "Yes", "No") )
To remove all pets that have ever bitten (even once), we can use a concise combination of group_by() and filter() in dplyr:
# Filter out pets with any history of biting safe_pets <- pet_data %>% group_by(Pet) %>% # Group all records by individual pet filter(all(Bite == "No")) %>% # Keep only groups where EVERY Bite entry is "No" ungroup() # Reset grouping to return a standard data frame
How this works:
group_by(Pet): Clusters all rows for each pet together, so we can evaluate their entire biting history as a group.filter(all(Bite == "No")): For each pet group, we only keep it if every entry in theBitecolumn is "No". If a pet has even one "Yes" (like the Tiger), this condition fails, and the entire group is excluded.ungroup(): Removes the pet grouping so the finalsafe_petsis a regular, ungrouped data frame.
Running this code will give you exactly your target dataset—only cows and dogs, with no trace of the tiger.
Alternative Explicit Approach
If you prefer a more step-by-step method, you can first identify safe pets, then filter the original data:
# Step 1: Get a list of pets that never bit safe_pet_names <- pet_data %>% group_by(Pet) %>% summarise(never_bitten = all(Bite == "No")) %>% filter(never_bitten) %>% pull(Pet) # Extract just the pet names as a vector # Step 2: Filter original data to keep only safe pets safe_pets <- pet_data %>% filter(Pet %in% safe_pet_names)
This achieves the same result, but the first method is more efficient and concise for most use cases.
内容的提问来源于stack exchange,提问作者peekay
相关产品推荐
相关产品推荐

