You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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 the Bite column 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 final safe_pets is 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:05:28