按两列对数据进行分组和过滤分组(dplyr) [英] group data and filter groups by two columns (dplyr)
本文介绍了按两列对数据进行分组和过滤分组(dplyr)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对使用 dplyr
过滤数据集有疑问.
I have a question regarding using dplyr
to filter a dataset.
我想按其 RestaurantID
对数据进行分组,然后对 wage> = 5
中中的
. wage&== 5
的所有组进行分组Year == 1992
I want to group data by its RestaurantID
and then filter()
all groups where the wage >= 5
in Year==1992
.
例如:
我有:
RestaurantID Year Wage
1 92 6
1 93 4
2 92 3
2 93 4
3 92 5
3 93 5
我想要的数据集(该数据集将所有在1992年的工资值等于> = 5的组保留下来)
Dataset I want (where it keeps all groups that had a wage value in 1992 that was >= 5)
RestaurantID Year Wage
1 92 6
1 93 4
3 92 5
3 93 5
我尝试过:
data %>% group_by("RestaurantID") %>% filter(any(Wage>= '5', Year =='92'))
但这给了我工资为> = 5
的所有行.
But this gives me all rows where wage is >=5
.
推荐答案
我们可以在不使用 filter
library(dplyr)
df1 %>%
filter(RestaurantID %in% RestaurantID[Year==92 & Wage>= 5])
# RestaurantID Year Wage
#1 1 92 6
#2 1 93 4
#3 3 92 5
#4 3 93 5
或与 base R
subset(df1, RestaurantID %in% RestaurantID[Year==92 & Wage>= 5])
# RestaurantID Year Wage
#1 1 92 6
#2 1 93 4
#5 3 92 5
#6 3 93 5
这篇关于按两列对数据进行分组和过滤分组(dplyr)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文