Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count days per year

Tags:

date

r

I have two dates

begin <- as.Date("2007-05-20")
end   <- as.Date("2010-06-13")

How can I count the days per year?

The output should maybe look like this

year   days
2007   226
2008   366
2009   365
2010   164
like image 380
speendo Avatar asked Feb 27 '12 13:02

speendo


2 Answers

Let's first create a proper date sequence:

R> bd <- as.Date("2007-05-20")
R> ed <- as.Date("2010-06-13")
R> seqd <- seq(bd, ed, by="1 day")
R> head(seqd)
[1] "2007-05-20" "2007-05-21" "2007-05-22" "2007-05-23" "2007-05-24" "2007-05-25"

We then create a helper function which, given a date, returns its year:

R> getYear <- function(d) as.POSIXlt(d)$year + 1900
R> getYear(head(seqd))
[1] 2007 2007 2007 2007 2007 2007

After that, we just call table() on what the helper returns from the date sequence:

R> table(getYear(seqd))

2007 2008 2009 2010 
 226  366  365  164 
like image 156
Dirk Eddelbuettel Avatar answered Nov 03 '22 00:11

Dirk Eddelbuettel


Or, alternatively create a data.frame with an additional column year (using Dirk's data):

dat = data.frame(seqd, year = strftime(seqd, "%Y"))
> head(dat)
        seqd year
1 2007-05-20 2007
2 2007-05-21 2007
3 2007-05-22 2007
4 2007-05-23 2007
5 2007-05-24 2007
6 2007-05-25 2007

and then use count from the plyr package:

require(plyr)
> count(dat, "year")
  year freq
1 2007  226
2 2008  366
3 2009  365
4 2010  164
like image 29
Paul Hiemstra Avatar answered Nov 03 '22 00:11

Paul Hiemstra