简单结合order、aggregate函数和dplyr即可实现,代码如下:
- library(dplyr)
- # 分组排序
- temp = iris[order(iris$Species, iris$Petal.Width), ]
- # 先用attach函数把temp的列变量名称加入到变量搜索范围内
- attach(temp)
- # 选择每组最后一条记录
- temp1 = aggregate(temp, by=list(Species, Petal.Width)
- ,FUN = last)
- # 选择每组第一条记录
- temp2 = aggregate(temp, by=list(Species, Petal.Width)
- ,FUN = first)
- # 选择每组第n=2条记录
- temp3 = aggregate(temp, by=list(Species, Petal.Width)
- ,FUN = nth, n=2)