Order dataframe by month

前端 未结 2 1758
梦毁少年i
梦毁少年i 2021-01-16 20:25

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          


        
2条回答
  •  遥遥无期
    2021-01-16 20:53

    Convert your "month" column into an ordered factor:

    factor(count_max$month, month.abb, ordered=TRUE)
    # [1] Apr Aug Dec Feb Jan Jul Jun Mar May Nov Oct Sep
    # Levels: Jan < Feb < Mar < Apr < May < Jun < Jul < Aug < Sep < Oct < Nov < Dec
    

    Example:

    count_max$month <- factor(count_max$month, month.abb, ordered=TRUE)
    count_max[order(count_max$month), ]
    #    month max.count
    # 5    Jan       482
    # 4    Feb       408
    # 8    Mar       483
    # 1    Apr       489
    # 9    May       369
    # 7    Jun       432
    # 6    Jul       344
    # 2    Aug       470
    # 12   Sep       474
    # 11   Oct       450
    # 10   Nov       492
    # 3    Dec       366
    

提交回复
热议问题