Francesc VE
Francesc VE

Reputation: 762

Making groups (group_by) depending on the column value with dplyr

I would like to make groups with dplyr depending on a condition. For example, if we have the following table:

A      B 
1      0
10     1
5      1
6      2

I would make groups when B = 0, another when B > 1, another when B > 2, and so on. The following approximation is wrong but maybe helps to understand:

df %>% 
   group_by(B > 0:2) %>% 
   summarize(Total = sum(A))

Upvotes: 4

Views: 71

Answers (1)

MrFlick
MrFlick

Reputation: 206167

Rows can't belong to more than one group when using group_by with dplyr. You'd need to map over values and repeatedly do the filtering. Here's one way to do that

purrr::map_df(0:2, ~df %>% filter(B>.x) %>% summarize(b_greater_than=.x, Total=sum(A)))
#   b_greater_than Total
# 1              0    21
# 2              1     6
# 3              2     0

Upvotes: 5

Related Questions