【问题标题】:loop over years and months循环数年和数月
【发布时间】:2019-06-14 16:03:40
【问题描述】:

我需要遍历日期列表并提取每个月(一年)的天数。 我没有找到在 r 中循环数月和数年的方法,有没有办法做到这一点?

以添加我的列表的一部分为例:

dates<-as.Date(c("2014-11-07" ,"2014-11-08","2014-11-09", "2014-11-10" ,
"2014-11-11" ,"2014-11-12" ,"2014-11-13" ,"2014-11-14", "2014-12-01",
"2014-12-02" ,"2014-12-03","2014-12-04", "2014-12-20" ,"2014-12-21", 
"2014-12-22","2015-01-01" ,"2015-01-02" ,"2015-01-03" ,"2015-01-04" ,
"2015-01-05"))

谢谢

【问题讨论】:

  • lubridate 也许?
  • 您能分享一下您的预期输出吗?

标签: r loops date


【解决方案1】:

您可以使用格式来获​​取年份和计数,即

i1 <- format(dates, format = '%Y')
table(i1)
#2014 2015 
#  15    5 

每月,每年,

table(format(dates, format = '%Y/%m'))

#2014/11 2014/12 2015/01 
#      8       7       5 

【讨论】:

  • 您更喜欢tapply(i1, i1, length) 而不是table(i1)? @Sotos
  • 哈哈哈……当然不是。我只是忘记了table。谢谢:)
  • 我想到了tapplylengths(split(i1, i1)) LOL...我喜欢星期一
  • 感谢分配! with: format (dates, format ='%Y-%m') 这正是我需要的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-30
  • 1970-01-01
  • 1970-01-01
  • 2013-11-18
  • 2016-08-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多