Home > Mobile >  Keep group in data frame if at least one group member meets condition
Keep group in data frame if at least one group member meets condition

Time:12-24

I am trying to filter out groups based on the condition that the group does not contain deviant – see the following dataset:

df <- structure(list(
  group_id = c(1, 1, 1, 2, 2, 2, 3, 3, 3), 
  sound = c("standard", "standard", "deviant", "standard", " standard ", " standard ", "deviant", " standard", " standard")),
  .Names = c("group_id", "soudn"),
  row.names = c(NA, -9L),
  class = "data.frame")

So I want to keep all of groups 1 and 3 as deviant is present in both (and this is the condition we are looking for), but remove group 2 since deviant isn’t present.

CodePudding user response:

library(dplyr)
df %>% 
  group_by(group_id) %>% 
  filter(any(soudn == "deviant"))
  • Related