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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With