2

I have a database of incidents by their date. I want to create a frequency table of incidents by month and year.

I am using this code below:

table(format(dat$Report.Date,"%m/%Y"))

01/2004 01/2005 01/2006 01/2007 01/2008 01/2009 01/2011 01/2012 01/2013 01/2014 ...

It doesn't sort chronologically. I tried sort() and order() and it did not work. I want this output:

01/2004, 02/2004, 03/2004 ... 12/2004, 1/2005...

What should I do?

Bryanzpope
  • 957
  • 1
  • 9
  • 20

1 Answers1

1

After creating the table, extract the 'month' and year separetely and do the sorting on the sequence

tbl <- table(format(dat$Report.Date,"%m/%Y"))
v1 <- as.numeric(substr(names(tbl), 1, 2))
v2 <- as.numeric(substr(names(tbl), 4, 8))
tbl[order(v2, ave(seq_along(v1), v1, FUN = seq_along))]

Or another option is to convert to yearmon object and then do the sorting

library(zoo)
tbl[order(as.yearmon(names(tbl), "%m/%Y"))]

data

set.seed(42)
dat <- data.frame(Report.Date = sample(seq(as.Date('2008-01-01'), 
            length.out = 100, by = '1 month')))
akrun
  • 874,273
  • 37
  • 540
  • 662