Select groups dependgin on values in two columns in dplyr

Viewed 28

Hello I have a df such as :

Groups COL2 COL3
G1 2 8
G1 3 4
G1 0 3
G2 1 3
G2 9 4
G3 3 89
G3 3 5
G4 1 7
G4 2 3

and I would like to select only groups if at least a row satisfies the two following conditions: COL2 < 3 and COL3 > 5. Thus here I would select only groups G1 and G4.

Groups COL2 COL3
G1 2 8
G1 3 4
G1 0 3
G4 1 7
G4 2 3

I tried:

df%>%
  group_by(Groups) %>%
  filter(any(COL2 <3) & any(COL3 >5)) %>%
1 Answers

If you want to select only the groups where at least a row satisfies both conditions (instead of having the conditions satisfied singularly at least once within the group), you can use the following.

# create vector of groups that satisfy the conditions
ok_groups <- (df %>%
  group_by(Groups) %>%
  filter(COL2 <3 & COL3 >5))$Groups

# filter original dataframe according to ok_groups
df %>% filter(Groups %in% ok_groups)

Output

> ok_groups
# [1] "G1" "G4"

> df %>% filter(Groups %in% ok_groups)
#   Groups COL2 COL3
# 1     G1    2    8
# 2     G1    3    4
# 3     G1    0    3
# 4     G4    1    7
# 5     G4    2    3

EDIT

I just insert a shorter solution here for future viewers

df %>%
  group_by(Groups) %>%
  filter(any(COL2 < 3 & COL3 > 5))
#   Groups COL2 COL3
# 1     G1    2    8
# 2     G1    3    4
# 3     G1    0    3
# 4     G4    1    7
# 5     G4    2    3
Related