Functionality of the order_by argument in dplyr::slice_max()

Viewed 1072

In the documentation for the slice_min() and slice_max() functions it says that the order_by argument can be a variable or function of variables to order by.

What is meant by function of variables, and how could this be applied in a practical sense? Could it, for example, be used to supply a custom order of categorical values?

I've tried what feels like an exhaustive search for info online, but to no avail, so I'm turning to you good folk. Thank you.

1 Answers

What is meant by function of variables, and how could this be applied in a practical sense?What is meant by function of variables, and how could this be applied in a practical sense?

I think the most common usage of "a function of variables" would be any function that you give as input columns from the data frame, and it returns a numeric result (or at least something that has a "max" value). Here are a couple examples:

## get the row with the highest product of Sepal.Length and Sepal.Width
iris %>% slice_max(Sepal.Length * Sepal.Width)
## here we use the function `*` and the variables `Sepal.Length` and `Sepal.Width`

iris %>% slice_max(nchar(Species))
## get the rows with the longest species name 
## here we use the function `nchar` and the variable `Species`

Could it, for example, be used to supply a custom order of categorical values?

Generally, if you want a custom order for categorical variables, we use factor and specify the order of the levels. Yes, you can use this within slice_max - the last factor level is considered the max:

iris %>% slice_max(Species)
## defaults to alphabetical order - all virginica rows returned

iris %>% slice_max(factor(Species, levels = c("versicolor", "virginica", "setosa")))
## if we make "setosa" the last/max level than setosa rows will be returned
Related