有没有办法在 R 的 aggregate() 函数中按多列排序输出?

Is there a way to order output by multiple columns within the aggregate() function in R?

我想使用聚合函数,但随后要根据 2 列(第一列,然后是另一列的子集)对输出进行排序(从小到大)。

这是一个例子:

test<-data.frame(c(sample(1:4),1),sample(2001:2005),11:15,c(letters[1:4],'a'),sample(101:105))
names(test)<-c("plot","year","age","spec","biomass")
test
  plot year age spec biomass
1    2 2001  11    a     102
2    4 2005  12    b     101
3    1 2004  13    c     105
4    3 2002  14    d     103
5    1 2003  15    a     104

aggregate(biomass~plot+year,data=test,FUN='sum')

这将创建仅包含从小到大排序的年份的输出。

  plot year biomass
1    2 2001     102
2    3 2002     103
3    1 2003     104
4    1 2004     105
5    4 2005     101

但我希望输出按情节和年份排序。

  plot year biomass
1    1 2003     104
2    1 2004     105
3    2 2001     102
4    3 2002     103
5    4 2005     101

谢谢!!

aggregate 函数 按列排序。切换参数的顺序以获得所需的排序:

# switch from
a0 <- aggregate(biomass~plot+year,data=test,FUN='sum')
# to
a  <- aggregate(biomass~year+plot,data=test,FUN='sum')

数据按照问题描述的方式排序。不需要进一步排序。


如果您想更改列的显示顺序 以完全匹配您想要的输出,请尝试a[,c(1,3,2)]。这种重新排序在计算上并不昂贵。我的理解是 data.frame 是指向列向量的指针列表;这只是对该列表重新排序。