如何在R中按年和月排序(使用Zoo包中的as.yearmon) [英] How to sort by year and month in R (using as.yearmon from zoo package)

查看:1048
本文介绍了如何在R中按年和月排序(使用Zoo包中的as.yearmon)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用年份和月份信息对向量进行排序.我从Date类型变量获取年份和月份.这是我要完成的工作的一个示例:

I'm trying to sort a vector with year and month information. I'm getting year and month from a Date type variable. Here's an example of what I'm trying to accomplish:

example <- as.Date(c("2010-04-22", "2010-04-26", "2010-04-26",
  "2010-06-04", "2010-06-07", "2010-06-18", "2010-06-21",
  "2010-07-14", "2010-07-16", "2010-07-30", "2010-08-20"))

mes_ano <- as.character(as.yearmon(as.Date(example)))

mes_ano <- factor(mes_ano, levels = c(unique(mes_ano),
 "mai 2010", "set 2010", "out 2010", "nov 2010"))

现在,我想按年份和月份对mes_ano进行排序,但是我不知道如何.

Now I would like to sort mes_ano by year and month, but I don't know how.

实际上,我的真正目标是对级别进行排序,因为我将使用ggplot2进行绘图,并且需要对级别进行排序.但是我认为,如果我只是问有关对向量进行排序的话,那将使我们的生活更加轻松.然后我可以弄清楚如何对级别进行排序.

Actually, my real goal is to sort the levels, since I'll make a plot with ggplot2 and I need the levels to be sorted. But I thought that it would make our life easier if I just asked about sorting a vector. Then I can figure out how to sort levels.

推荐答案

我想您要使用葡萄牙语月份的名称.走吧:

I suppose you want to use the Potuguese month names. Let's go:

您的数据:

example <- as.Date(c("2010-04-22", "2010-04-26", "2010-04-26",
                     "2010-06-04", "2010-06-07", "2010-06-18", "2010-06-21",
                     "2010-07-14", "2010-07-16", "2010-07-30", "2010-08-20"))

我们需要一个具有以下名称的向量:

We need a vector with these names:

port_mon <- c("jan", "fev", "mar", "abr", "mai", "jun",
              "jul", "ago", "set", "out", "nov", "dez")

现在,对数据进行排序:

Now, sort the data:

ex_sorted <- sort(example)

用葡萄牙语选择正确的月份名称:

Choose the correct month names in Portuguese:

month_names <- port_mon[as.numeric(format(ex_sorted, "%m"))]

组合月份和年份:

mes_ano <- paste(month_names, format(ex_sorted, "%Y"))

创建因素:

mes_ano_fac <- factor(as.yearmon(ex_sorted), labels = unique(mes_ano)) 

图(出于说明目的,在y轴上具有无意义的数据):

Plot (with meaningless data on the y-axis for illustration purposes):

library(ggplot)

qplot(x = mes_ano_fac, y = seq(length(example)))

这篇关于如何在R中按年和月排序(使用Zoo包中的as.yearmon)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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