每天计数天数 [英] Count days per year

查看:118
本文介绍了每天计数天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个日期

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

如何计数每年的日子?

输出应该看起来像这样

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"

然后我们创建一个帮助函数,给定一个日期,返回其年份: p>

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

之后那我们只需要从日期序列中调用 table()

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 

这篇关于每天计数天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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