首页 > 解决方案 > 如何一次性汇总几年数据的天数?

问题描述

我有类似的数据。我想一次性汇总当天(我不确定“一次性付款”这个词是否正确)并创建一个新列“日期”,以便新列一次性汇总 3 年数据的数量以升序排列。

    year  month day
    2011    1   5
    2011    2   14
    2011    8   21
    2012    2   24
    2012    3   3
    2012    4   4
    2012    5   6
    2013    2   14
    2013    5   17
    2013    6   24

我做了这段代码,但结果是错误的,而且它也太长了。由于 2 月只有 28 天,因此不能正确计算 2 月。有没有更短的方法?

    cday <- function(data,syear=2011,smonth=1,sday=1){
       year <- data[1]
      month <- data[2]
      day <- data[3]
      cmonth <- c(0,31,28,31,30,31,30,31,31,30,31,30,31)
      date <- (year-syear)*365+sum(cmonth[1:month])+day
      for(yr in c(syear:year)){
      if(yr==year){
      if(yr%%4==0&&month>2){date<-date+1}
       }else{
         if(yr%%4==0){date<-date+1}
         }
       }
      return(date)
    }
   op10$day.no <- apply(op10[,c("year","month","day")],1,cday)



I expect the result like this:

    year  month day  date
    2011    1   5     5
    2011    1   14    14
    2011    1   21    21
    2011    1   24    24
    2011    2   3     31
    2011    2   4     32
    2011    2   6     34
    2011    2   14    42
    2011    2   17    45
    2011    2   24    52

感谢您的帮助!!

标签: r

解决方案


使用Date类。日期和时间很复杂,请寻找工具来为您执行此操作,而不是自己编写。选择您想要的任何一个:

df$date = with(df, as.Date(paste(year, month, day, sep = "-")))

df$julian_day = as.integer(format(df$date, "%j"))
df$days_since_2010 = as.integer(df$date - as.Date("2010-12-31"))

df
#    year month day       date julian_day days_since_2010
# 1  2011     1   5 2011-01-05          5               5
# 2  2011     2  14 2011-02-14         45              45
# 3  2011     8  21 2011-08-21        233             233
# 4  2012     2  24 2012-02-24         55             420
# 5  2012     3   3 2012-03-03         63             428
# 6  2012     4   4 2012-04-04         95             460
# 7  2012     5   6 2012-05-06        127             492
# 8  2013     2  14 2013-02-14         45             776
# 9  2013     5  17 2013-05-17        137             868
# 10 2013     6  24 2013-06-24        175             906
# using this data
df = read.table(text = "year  month day
    2011    1   5
    2011    2   14
    2011    8   21
    2012    2   24
    2012    3   3
    2012    4   4
    2012    5   6
    2013    2   14
    2013    5   17
    2013    6   24", header = TRUE)

这都是使用base R。如果您经常处理日期和时间,您可能还想查看lubridate包。


推荐阅读