How to define holidays for is.holiday() chron package in R

后端 未结 3 859
感情败类
感情败类 2020-12-29 14:42

I\'m trying to use chron\'s is.holiday() function, but I\'m having trouble getting it to work. The documentation says to modify the .Holiday

3条回答
  •  执笔经年
    2020-12-29 15:03

    This is non-trivial and probably deserves to be referred to the chron maintainer as a bug.

    library(chron)
    library(timeDate)
    hlist <- c("CAVictoriaDay","CACanadaDay","CALabourDay")
    (ss <- dates(sapply(sapply(hlist,holiday,year=2011),as.Date)))
    .Holidays <- ss
    

    (Someone who actually works with dates in R more often than I do probably has a more elegant solution for the preceding stuff, without that double-sapply thing ...)

    But this doesn't change the important thing, which is the version of Holidays in the chron namespace:

    chron::.Holidays  ## no change
    

    The clue is here: Override a function that is imported in a namespace

    Namespace magic:

    unlockBinding(".Holidays", as.environment("package:chron"))
    assignInNamespace(".Holidays", .Holidays, ns="chron", 
        envir=as.environment("package:chron"))
    assign(".Holidays", .Holidays, as.environment("package:chron"))
    lockBinding(".Holidays", as.environment("package:chron"))
    

    Now look, and it has worked:

    chron::.Holidays
    

    Test it out:

    yrvec <- seq.Date(as.Date("2011-01-01"),
                        as.Date("2011-12-31"),by="day")
    plot(is.holiday(yrvec),axes=FALSE)
    axis.Date(side=1,yrvec)
    

提交回复
热议问题