I am trying to write a little top_n_by function in dplyr.
topNby = function(df, dim, byDim, n) {
return( group_by(df, as.symbol(dim)) %>%
summarise(topDim = sum(byDim)) %>%
arrange(desc(topDim)) %>%
slice(1:n) %>%
.[[dim]] %>% as.character()
)
}
But group_by
throw back an error:
Error in mutate_impl(.data, dots) : object 'yourDim' not found
I also tried without as.symbol
but with no success. What is the correct way to use group_by
when you want to be able to dynamically set the column(s) of grouping.
(I am pretty sure this must have been answered elsewhere but cannot find a satisfying answer...)