Is there an R package that will handle POSIX objects and return the nth N-day of the week?

后端 未结 2 1823
故里飘歌
故里飘歌 2021-01-16 12:13

I have written a function which, when provided a range of dates, the name of a particular day of the week and the occurrence of that day in a given month (for instance, the

相关标签:
2条回答
  • 2021-01-16 12:54

    Using the function nextfri whose one line source is shown in the zoo Quick Reference vignette in the zoo package the following gives the second Friday of d where d is the "Date" of the first of the month:

    > library(zoo)
    > d <- as.Date(c("2011-09-01", "2011-10-01"))
    > nextfri(d) + 7
    [1] "2011-09-09" "2011-10-14"
    

    (nextfri is not part of the zoo package -- you need to enter it yourself -- but its only one line)

    The following gives the day of the week where 0 is Sunday, 1 is Monday, etc.

    > as.POSIXlt(d)$wday
    [1] 4 6
    

    If you really are dealing exclusively with dates rather than date-times then you ought to be using "Date" class rather than "POSIXt" classes in order to avoid time zone errors. See the article in R News 4/1.

    0 讨论(0)
  • 2021-01-16 13:10

    The timeDate package has some of that functionality; I based this little snippet of code on some code that package. This is for Dates, timeDate has underlying POSIX types.

    nthNdayInMonth <- function(date,nday = 1, nth = 1){
      wday <- (as.integer(date) - 3) %% 7
      r <- (as.integer(date) + (nth -1) * 7 + (nday - wday)%%7)
      as.Date(r,"1970-01-01")
    }
    
    0 讨论(0)
提交回复
热议问题