按组获取顶级值 [英] Getting the top values by group

查看:86
本文介绍了按组获取顶级值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个示例数据框架:

Here's a sample data frame:

d <- data.frame(
  x   = runif(90),
  grp = gl(3, 30)
) 

我想要包含 cp的每个值的 d 的子集包含前五个值 x 的行

I want the subset of d containing the rows with the top 5 values of x for each value of grp.

使用base-R,我的方法是这样的:

Using base-R, my approach would be something like:

ordered <- d[order(d$x, decreasing = TRUE), ]    
splits <- split(ordered, ordered$grp)
heads <- lapply(splits, head)
do.call(rbind, heads)
##              x grp
## 1.19 0.8879631   1
## 1.4  0.8844818   1
## 1.12 0.8596197   1
## 1.26 0.8481809   1
## 1.18 0.8461516   1
## 1.29 0.8317092   1
## 2.31 0.9751049   2
## 2.34 0.9269764   2
## 2.57 0.8964114   2
## 2.58 0.8896466   2
## 2.45 0.8888834   2
## 2.35 0.8706823   2
## 3.74 0.9884852   3
## 3.73 0.9837653   3
## 3.83 0.9375398   3
## 3.64 0.9229036   3
## 3.69 0.8021373   3
## 3.86 0.7418946   3

使用 dplyr ,我预计这将工作:

Using dplyr, I expected this to work:

d %>%
  arrange_(~ desc(x)) %>%
  group_by_(~ grp) %>%
  head(n = 5)

但它只返回整体前5行。

but it only returns the overall top 5 rows.

交换 head for top_n 返回整个 d

d %>%
  arrange_(~ desc(x)) %>%
  group_by_(~ grp) %>%
  top_n(n = 5)

如何获得正确的子集?

推荐答案

?top_n ,用于排序的变量[...] 默认为tbl中的最后一个变量 。您的数据集中的最后一个变量是grp,它不是您希望排名的变量,也就是为什么您的 top_n 尝试返回整个d。因此,如果您希望在数据集中排列x,则需要指定 wt = x

From ?top_n, "The variable to use for ordering [...] defaults to the last variable in the tbl". The last variable in your data set is "grp", which is not the variable you wish to rank, and which is why your top_n attempt "returns the whole of d". Thus, if you wish to rank by "x" in your data set, you need to specify wt = x.

set.seed(123)
d <- data.frame(
  x   = runif(90),
  grp = gl(3, 30))

d %>%
  group_by(grp) %>%
  top_n(n = 5, wt = x)
#            x grp
# 1  0.9404673   1
# 2  0.9568333   1
# 3  0.8998250   1
# 4  0.9545036   1
# 5  0.9942698   1
# 6  0.9630242   2
# 7  0.9022990   2
# 8  0.8578277   2
# 9  0.7989248   2
# 10 0.8950454   2
# 11 0.8146400   3
# 12 0.8123895   3
# 13 0.9849570   3
# 14 0.8930511   3
# 15 0.8864691   3

这篇关于按组获取顶级值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆