按组选择前N个值

这是对r-help邮件列表上询问的问题的答复。


这里有很多示例,这些示例如何通过分组使用来查找最高值sql,因此我想可以很容易地使用R sqldf包将这些知识转换为知识。


例如:mtcars按分组时cyl,这是的每个不同值的前三条记录cyl。请注意,在这种情况下,不包括领带,但是最好显示一些其他处理领带的方法。


                     mpg cyl  disp  hp drat    wt  qsec vs am gear carb ranks

Toyota Corona       21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1   2.0

Volvo 142E          21.4   4 121.0 109 4.11 2.780 18.60  1  1    4    2   1.0

Valiant             18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1   2.0

Merc 280            19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4   3.0

Merc 280C           17.8   6 167.6 123 3.92 3.440 18.90  1  0    4    4   1.0

Cadillac Fleetwood  10.4   8 472.0 205 2.93 5.250 17.98  0  0    3    4   1.5

Lincoln Continental 10.4   8 460.0 215 3.00 5.424 17.82  0  0    3    4   1.5

Camaro Z28          13.3   8 350.0 245 3.73 3.840 15.41  0  0    3    4   3.0

如何找到每组的前N个记录(最大或最小)?


Cats萌萌
浏览 505回答 3
3回答

烙印99

随便按什么排序(例如,mpg,问题尚不清楚)mt <- mtcars[order(mtcars$mpg), ]然后使用by函数获取每组中的前n行d <- by(mt, mt["cyl"], head, n=4)如果希望结果为data.frame:Reduce(rbind, d)编辑: 处理关系比较困难,但是如果需要所有关系:by(mt, mt["cyl"], function(x) x[rank(x$mpg) %in% sort(unique(rank(x$mpg)))[1:4], ])另一种方法是根据其他一些信息(例如,mt <- mtcars[order(mtcars$mpg, mtcars$hp), ]by(mt, mt["cyl"], head, n=4)

catspeake

dplyr 绝招mtcars %>%&nbsp;arrange(desc(mpg)) %>%&nbsp;group_by(cyl) %>% slice(1:2)&nbsp;mpg&nbsp; &nbsp;cyl&nbsp; disp&nbsp; &nbsp; hp&nbsp; drat&nbsp; &nbsp; wt&nbsp; qsec&nbsp; &nbsp; vs&nbsp; &nbsp; am&nbsp; gear&nbsp; carb&nbsp; <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>1&nbsp; 33.9&nbsp; &nbsp; &nbsp;4&nbsp; 71.1&nbsp; &nbsp; 65&nbsp; 4.22 1.835 19.90&nbsp; &nbsp; &nbsp;1&nbsp; &nbsp; &nbsp;1&nbsp; &nbsp; &nbsp;4&nbsp; &nbsp; &nbsp;12&nbsp; 32.4&nbsp; &nbsp; &nbsp;4&nbsp; 78.7&nbsp; &nbsp; 66&nbsp; 4.08 2.200 19.47&nbsp; &nbsp; &nbsp;1&nbsp; &nbsp; &nbsp;1&nbsp; &nbsp; &nbsp;4&nbsp; &nbsp; &nbsp;13&nbsp; 21.4&nbsp; &nbsp; &nbsp;6 258.0&nbsp; &nbsp;110&nbsp; 3.08 3.215 19.44&nbsp; &nbsp; &nbsp;1&nbsp; &nbsp; &nbsp;0&nbsp; &nbsp; &nbsp;3&nbsp; &nbsp; &nbsp;14&nbsp; 21.0&nbsp; &nbsp; &nbsp;6 160.0&nbsp; &nbsp;110&nbsp; 3.90 2.620 16.46&nbsp; &nbsp; &nbsp;0&nbsp; &nbsp; &nbsp;1&nbsp; &nbsp; &nbsp;4&nbsp; &nbsp; &nbsp;45&nbsp; 19.2&nbsp; &nbsp; &nbsp;8 400.0&nbsp; &nbsp;175&nbsp; 3.08 3.845 17.05&nbsp; &nbsp; &nbsp;0&nbsp; &nbsp; &nbsp;0&nbsp; &nbsp; &nbsp;3&nbsp; &nbsp; &nbsp;26&nbsp; 18.7&nbsp; &nbsp; &nbsp;8 360.0&nbsp; &nbsp;175&nbsp; 3.15 3.440 17.02&nbsp; &nbsp; &nbsp;0&nbsp; &nbsp; &nbsp;0&nbsp; &nbsp; &nbsp;3&nbsp; &nbsp; &nbsp;2
打开App,查看更多内容
随时随地看视频慕课网APP