首页 > 解决方案 > dplyr::slice_max() 中 order_by 参数的功能

问题描述

在and函数的文档中,它说参数可以是要排序的变量或变量的函数。slice_min()slice_max()order_by

变量函数是什么意思,如何在实际意义上应用?例如,它可以用于提供分类值的自定义顺序吗?

我已经尝试过在网上进行详尽的信息搜索,但无济于事,所以我转向你们这些好人。谢谢你。

标签: rdplyr

解决方案


变量函数是什么意思,如何实际应用?变量函数是什么意思,如何实际应用?

我认为“变量函数”的最常见用法是您从数据框中作为输入列提供的任何函数,它返回一个数字结果(或至少具有“最大值”值的东西)。这里有几个例子:

## 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`

例如,它可以用于提供分类值的自定义顺序吗?

通常,如果您想要分类变量的自定义顺序,我们使用factor并指定级别的顺序。是的,您可以在其中使用它slice_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

推荐阅读