代码之家  ›  专栏  ›  技术社区  ›  spore234

在一系列日期中查找一个月的最后一天

  •  2
  • spore234  · 技术社区  · 6 年前

    ds <- seq(as.Date("2011-02-01"), length=100, by="day")
    

    我想找出每个月最后几天的指数

    我可以这样做

    last_day <- seq(as.Date("2011-02-01"), length=10, by="1 month") - 1
    
    which(ds %in% last_day)
    

    例如,我删除了二月的最后一天

    ds[ds == as.Date('2011-02-28')] <- NA
    

    如何根据向量中的日期查找每个月的最后一个? 日期跨越了好几年。

    4 回复  |  直到 6 年前
        1
  •  5
  •   nicola    6 年前

    尝试:

    which(ave(as.numeric(ds),format(ds,"%Y%m"),FUN=function(x) x==max(x))==1)
    
        2
  •  3
  •   Ronak Shah    6 年前

    我们可以 group_by 选择月份 max 每月的日期

    library(zoo)
    library(dplyr)
    
    data.frame(ds) %>%
      group_by(month = as.yearmon(ds)) %>%
      slice(which.max(ds))
    
    
    #        ds         month        
    #     <date>     <S3: yearmon>
    #1 2011-02-27     Feb 2011     
    #2 2011-03-31     Mar 2011     
    #3 2011-04-30     Apr 2011     
    #4 2011-05-11     May 2011  
    

    如果我们想要指数,我们可以

    library(zoo) 
    which(ds %in% unique(ave(ds, as.yearmon(ds), FUN = max)))
    #[1] 27 58 88 99
    
        3
  •  1
  •   Enrico Schumann    6 年前

    功能 nth_day datetimeutils (我坚持) 允许您获取一个月的最后一天。它处理不了 NA

    library("datetimeutils")
    ds <- seq(as.Date("2011-02-01"), length = 100, by = "day")
    
    nth_day(ds, n = "last")
    ## [1] "2011-02-28" "2011-03-31" "2011-04-30" "2011-05-11"
    
    nth_day(ds, n = "last", index = TRUE)
    ## [1]  28  59  89 100
    
        4
  •  0
  •   phiver    6 年前

    使用 endpoints 从xts包:

    ds <- seq(as.Date("2011-02-01"), length=100, by="day")
    ds[ds == as.Date('2011-02-28')] <- NA
    
    
    library(xts)
    #need to remove NA's. xts can handle dates that are not there, but doesn't like NA's
    ep <- endpoints(xts(ds[!is.na(ds)], order.by = ds[!is.na(ds)]), on = "months")
    ds[ep]
    [1] "2011-02-27" "2011-03-30" "2011-04-29" "2011-05-10"