Damien Dotta
Damien Dotta

Reputation: 939

Filter tibble by group

Given my tibble test below, I would like to keep only the rows for which siren_ent is equal to "A".
The condition is : regsiege_fare column is never equal to region_etab whereas when siren_ent is equal to "B", there is at least one row where region_etab = regsiege_fare.

Many thanks in advance

test <- tibble(
  siren_ent = c("A","A","A","B","B"),
  region_etab = c("93","11","24","24","32"),
  regsiege_fare = c("28","28","28","32","32")
)

Upvotes: 1

Views: 98

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101034

A base R option using subset

subset(
    test,
    !siren_ent %in% siren_ent[region_etab == regsiege_fare]
)

gives

# A tibble: 3 x 3
  siren_ent region_etab regsiege_fare
  <chr>     <chr>       <chr>
1 A         93          28
2 A         11          28
3 A         24          28

Upvotes: 0

akrun
akrun

Reputation: 886938

May be this

library(dplyr)
test %>% 
    group_by(siren_ent) %>% 
    filter(!any(region_etab == regsiege_fare)) %>%
    ungroup

-output

# A tibble: 3 x 3
  siren_ent region_etab regsiege_fare
  <chr>     <chr>       <chr>        
1 A         93          28           
2 A         11          28           
3 A         24          28          

Upvotes: 2

Related Questions