Manoel Galdino
Manoel Galdino

Reputation: 2396

How to sort by year and month in R (using as.yearmon from zoo package)

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"))

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

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.

Upvotes: 0

Views: 2204

Answers (1)

Sven Hohenstein
Sven Hohenstein

Reputation: 81733

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

Your data:

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"))]

Combine months and years:

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

Create factor:

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

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

library(ggplot)

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

enter image description here

Upvotes: 1

Related Questions