0

I know it works well as follows:

library(dplyr)
df %>% group_by(customer_name) 
   %>% mutate(my_ranks = order(order_values, order_dates, decreasing=TRUE))

Source: local data frame [5 x 4]
Groups: customer_name

  customer_name order_dates order_values my_ranks
1          John  2010-11-01           15        3
2           Bob  2008-03-25           12        1
3          Alex  2009-11-15            5        1
4          John  2012-08-06           15        2
5          John  2015-05-07           20        1

My problem is that I just don't know how to use a column to finish this work.

Example:

group_by_colname <- "customer_name"
order_by_colname <- "order_values"
df %>% group_by(df[[group_by_colname]]) 
   %>% mutate(my_ranks = order(df[[order_by_colname]], decreasing=TRUE))

It doesn't work. I know the problem is we can not use df's order-by-colname, but I didn't know how to solve this problem.

  • 1
    Why not using `arrange`? It would be great to post some example data and desired output. This might help: https://stackoverflow.com/questions/43832434/arrange-within-a-group-with-dplyr – AntoniosK Jan 28 '18 at 16:38
  • `df %>% group_by(df[[group_by_colname]])` doesn't work because the first argument of `group_by` is the df, and the second argument is the variable you want to group. You're already piping in df as the first argument, so just do `df %>% group_by(group_by_colname)`. As for the second line, as @AntoniosK, just use `arrange`. – Phil Jan 28 '18 at 17:02

0 Answers0