group_by slice_top with different n

I want to group_by dataframe and select top n values for each group. But I want n differ for each group.
I write following code:
dt = d %>% group_by(USER_ID)%>% slice_head(n = min(top))
but it does not work. Is any idea how to solve it?

I find out solution:

  1. group data by ID and arrange. then create new variable - "rownumber":
    d %<>% group_by(USER_ID)%>% mutate( rownumber = row_number())
  2. filter where rownumber <= top
    d %<>% filter(rownumber<=top)
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.