按月订购数据帧 [英] Order dataframe by month

查看:120
本文介绍了按月订购数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经计算出此数据中每个月的最大计数.

I have calculated the maximum counts per month in this data.frame:

counts <- data.frame(year = sort(rep(2000:2009, 12)), month = rep(month.abb,10), count = sample(1:500, 120, replace = T))

library(plyr)
count_max <- ddply(counts, .(month), summarise, max.count = max(count))


  month max.count
1    Apr       470
2    Aug       389
3    Dec       446
4    Feb       487
5    Jan       473
6    Jul       460
7    Jun       488
8    Mar       449
9    May       488
10   Nov       464
11   Oct       483
12   Sep       394

我现在想按month.abb向量对count_max进行排序,以使month处于通常的Jan-Dec顺序.这是我尝试过的:

I now want to sort count_max by the month.abb vector, so that month is in the usual order Jan-Dec. This is what I tried:

count_max[match(count_max$month, month.abb),]

...但是没有用.如何按1月-12月的顺序安排count_max$month?

...but it didn't work. How can I arrange count_max$month in the order Jan-Dec?

推荐答案

不进行转换的替代方案:

An alternate without conversion:

count_max[order(match(count_max$month, month.abb)), ]
#    month max.count
# 5    Jan       466
# 4    Feb       356
# 8    Mar       496
# 1    Apr       489
# 9    May       498
# 7    Jun       497
# 6    Jul       491
# 2    Aug       446
# 12   Sep       414
# 11   Oct       490
# 10   Nov       416
# 3    Dec       475         

请注意,在您的示例中,match(count...)返回给定月份在month.abb中的位置,这是您要依据的位置.您真的很接近,但是您没有按该向量进行排序,而是对其进行了子集化.因此,例如,八月是原始DF中的第二个值,但month.abb中的第八个值,因此子集向量中第二个值的匹配值为8,这意味着您将把您的原始数据帧(在您的情况下为3月)位于新DF的第二个位置,而不是将原始DF中的第二行排在新DF的第8个位置.

Note that in your example, match(count...) returns the position of a given month in month.abb, which is what you want to sort by. You came real close, but instead of sorting by that vector, you subsetted by it. So, for example, August is the 2nd value in your original DF, but the 8th value in month.abb, so the match value for the 2nd value in your subset vector is 8, which means you are going to put the 8th row of your original data frame (in your case March), into the second position of your new DF, instead of ranking the 2nd row in your original DF into 8th position of the new one.

这种区别有点让人费解,但是如果您认为通过它可以理解.

The distinction is a bit of a brain twister, but if you think it through it should make sense.

这篇关于按月订购数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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