Reputation: 4635
I try to filter the group that contains min x value in them. But I would like to keep the entire group.
Similar post in here but not for min value
filtering
Remove groups that contain certain strings
So I try
df <-data.frame(x=c(250,240,233,250,100,10,250,100,1),gr=gl(3,3))
> df
x gr
1 250 1
2 240 1
3 233 1
4 250 2
5 100 2
6 10 2
7 250 3
8 100 3
9 1 3
df%>%
group_by(gr)%>%
filter(all(x==min(x)))
Returning the empty df. Why ?
the expected output would be
x gr
7 250 3
8 100 3
9 1 3
Upvotes: 1
Views: 47
Reputation: 388807
A base R approach could be finding the corresponding gr
of min
imum x
and then filtering the dataframe based on that.
df[df$gr %in% df$gr[which.min(df$x)],]
# x gr
#7 250 3
#8 100 3
#9 1 3
Or similar to your and @Wen's approach using ave
df[ave(df$x, df$gr, FUN = function(i) any(i == min(df$x))) == 1, ]
Upvotes: 1
Reputation: 323226
You should using any
instead of all
df%>%group_by(gr)%>%filter(any(x==min(df$x)))
# A tibble: 3 x 2
# Groups: gr [1]
x gr
<dbl> <fctr>
1 250 3
2 100 3
3 1 3
Upvotes: 1