I need help writing a function to count the number of holidays within a time period using lubridate in R










1














I am attempting to write a function that counts the number of holidays a person worked in my organization between their start and term date in the year 2017. My organization recognized 6 holidays that year-



New Years Day- 2017-01-02



Memorial Day- 2017-05-29



Independence Day - 2017-07-04



Labor Day - 2017-09-04



Thanksgiving Day- 2017-11-23



Christmas day - 2017-12-25



I used lubridate to combine my year-month-day columns into complete dates using lubridate and dyplr like so:



dates<- data %>% mutate("Term Date" = make_date(month = `Term Month`,
day = data$`Term Day`,
year =data$`Term Year`),
"Start Date"= make_date(month = data$`Start Month`,
day = data$`Start Day`,
year = data$`Start Year`))


I then went on to attempt to write my function.



holidays <- function(x)
z<- 0
if( ymd("2017-01-01") %within% interval(dates$`Start Date`, dates$`Term Date`))
z <- z + 1

print(z)



This was only my first step. My goal was to first make my function work for new years and then continue to build in other holidays step by step using if statements.I was unable to get the apply function to work correctly and am unsure if my function even works. I attempted to apply the function like so :



apply(dates,2,holidays)


But got an error argument.



Does anyone have any advice?










share|improve this question




























    1














    I am attempting to write a function that counts the number of holidays a person worked in my organization between their start and term date in the year 2017. My organization recognized 6 holidays that year-



    New Years Day- 2017-01-02



    Memorial Day- 2017-05-29



    Independence Day - 2017-07-04



    Labor Day - 2017-09-04



    Thanksgiving Day- 2017-11-23



    Christmas day - 2017-12-25



    I used lubridate to combine my year-month-day columns into complete dates using lubridate and dyplr like so:



    dates<- data %>% mutate("Term Date" = make_date(month = `Term Month`,
    day = data$`Term Day`,
    year =data$`Term Year`),
    "Start Date"= make_date(month = data$`Start Month`,
    day = data$`Start Day`,
    year = data$`Start Year`))


    I then went on to attempt to write my function.



    holidays <- function(x)
    z<- 0
    if( ymd("2017-01-01") %within% interval(dates$`Start Date`, dates$`Term Date`))
    z <- z + 1

    print(z)



    This was only my first step. My goal was to first make my function work for new years and then continue to build in other holidays step by step using if statements.I was unable to get the apply function to work correctly and am unsure if my function even works. I attempted to apply the function like so :



    apply(dates,2,holidays)


    But got an error argument.



    Does anyone have any advice?










    share|improve this question


























      1












      1








      1







      I am attempting to write a function that counts the number of holidays a person worked in my organization between their start and term date in the year 2017. My organization recognized 6 holidays that year-



      New Years Day- 2017-01-02



      Memorial Day- 2017-05-29



      Independence Day - 2017-07-04



      Labor Day - 2017-09-04



      Thanksgiving Day- 2017-11-23



      Christmas day - 2017-12-25



      I used lubridate to combine my year-month-day columns into complete dates using lubridate and dyplr like so:



      dates<- data %>% mutate("Term Date" = make_date(month = `Term Month`,
      day = data$`Term Day`,
      year =data$`Term Year`),
      "Start Date"= make_date(month = data$`Start Month`,
      day = data$`Start Day`,
      year = data$`Start Year`))


      I then went on to attempt to write my function.



      holidays <- function(x)
      z<- 0
      if( ymd("2017-01-01") %within% interval(dates$`Start Date`, dates$`Term Date`))
      z <- z + 1

      print(z)



      This was only my first step. My goal was to first make my function work for new years and then continue to build in other holidays step by step using if statements.I was unable to get the apply function to work correctly and am unsure if my function even works. I attempted to apply the function like so :



      apply(dates,2,holidays)


      But got an error argument.



      Does anyone have any advice?










      share|improve this question















      I am attempting to write a function that counts the number of holidays a person worked in my organization between their start and term date in the year 2017. My organization recognized 6 holidays that year-



      New Years Day- 2017-01-02



      Memorial Day- 2017-05-29



      Independence Day - 2017-07-04



      Labor Day - 2017-09-04



      Thanksgiving Day- 2017-11-23



      Christmas day - 2017-12-25



      I used lubridate to combine my year-month-day columns into complete dates using lubridate and dyplr like so:



      dates<- data %>% mutate("Term Date" = make_date(month = `Term Month`,
      day = data$`Term Day`,
      year =data$`Term Year`),
      "Start Date"= make_date(month = data$`Start Month`,
      day = data$`Start Day`,
      year = data$`Start Year`))


      I then went on to attempt to write my function.



      holidays <- function(x)
      z<- 0
      if( ymd("2017-01-01") %within% interval(dates$`Start Date`, dates$`Term Date`))
      z <- z + 1

      print(z)



      This was only my first step. My goal was to first make my function work for new years and then continue to build in other holidays step by step using if statements.I was unable to get the apply function to work correctly and am unsure if my function even works. I attempted to apply the function like so :



      apply(dates,2,holidays)


      But got an error argument.



      Does anyone have any advice?







      r function apply data-science lubridate






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 12 '18 at 23:17









      Harro Cyranka

      1,2071513




      1,2071513










      asked Nov 12 '18 at 22:57









      Abe KassemAbe Kassem

      62




      62






















          1 Answer
          1






          active

          oldest

          votes


















          0














          Putting the holidays in a vector:



          holidays <- as.Date(c('2017-01-02', '2017-05-29', '2017-07-04', '2017-09-04', '2017-11-23', '2017-12-25'))


          Extracting month and day (to make it independent of year), "%j" stands for day of year:



          holidays <- format(as.Date(holidays), "%j")


          Generating some random data to test (1000 uniformly distributed work entries in 2017, 5 employees):



          d <- data.frame(
          'date' = as.Date(as.integer(runif(1000, 17167, 17531)), origin = '1970-01-01'),
          'emp' = sample(LETTERS[1:5], 1000, replace = T)
          )


          Filtering out the holidays:



          h <- d[format(d$date, "%j") %in% holidays, ]


          Counting number of holidays worked per employee using aggregate():



          aggregate(h$date, list(h$emp), length)

          # Group.1 x
          #1 A 3
          #2 B 4
          #3 C 2
          #4 D 5
          #5 E 1


          NB: will work for 2017, but won't work for leap years (one workaround that doesn't involve altering the code too too much is to change the year in the holiday vector manually).






          share|improve this answer




















            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53271317%2fi-need-help-writing-a-function-to-count-the-number-of-holidays-within-a-time-per%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            Putting the holidays in a vector:



            holidays <- as.Date(c('2017-01-02', '2017-05-29', '2017-07-04', '2017-09-04', '2017-11-23', '2017-12-25'))


            Extracting month and day (to make it independent of year), "%j" stands for day of year:



            holidays <- format(as.Date(holidays), "%j")


            Generating some random data to test (1000 uniformly distributed work entries in 2017, 5 employees):



            d <- data.frame(
            'date' = as.Date(as.integer(runif(1000, 17167, 17531)), origin = '1970-01-01'),
            'emp' = sample(LETTERS[1:5], 1000, replace = T)
            )


            Filtering out the holidays:



            h <- d[format(d$date, "%j") %in% holidays, ]


            Counting number of holidays worked per employee using aggregate():



            aggregate(h$date, list(h$emp), length)

            # Group.1 x
            #1 A 3
            #2 B 4
            #3 C 2
            #4 D 5
            #5 E 1


            NB: will work for 2017, but won't work for leap years (one workaround that doesn't involve altering the code too too much is to change the year in the holiday vector manually).






            share|improve this answer

























              0














              Putting the holidays in a vector:



              holidays <- as.Date(c('2017-01-02', '2017-05-29', '2017-07-04', '2017-09-04', '2017-11-23', '2017-12-25'))


              Extracting month and day (to make it independent of year), "%j" stands for day of year:



              holidays <- format(as.Date(holidays), "%j")


              Generating some random data to test (1000 uniformly distributed work entries in 2017, 5 employees):



              d <- data.frame(
              'date' = as.Date(as.integer(runif(1000, 17167, 17531)), origin = '1970-01-01'),
              'emp' = sample(LETTERS[1:5], 1000, replace = T)
              )


              Filtering out the holidays:



              h <- d[format(d$date, "%j") %in% holidays, ]


              Counting number of holidays worked per employee using aggregate():



              aggregate(h$date, list(h$emp), length)

              # Group.1 x
              #1 A 3
              #2 B 4
              #3 C 2
              #4 D 5
              #5 E 1


              NB: will work for 2017, but won't work for leap years (one workaround that doesn't involve altering the code too too much is to change the year in the holiday vector manually).






              share|improve this answer























                0












                0








                0






                Putting the holidays in a vector:



                holidays <- as.Date(c('2017-01-02', '2017-05-29', '2017-07-04', '2017-09-04', '2017-11-23', '2017-12-25'))


                Extracting month and day (to make it independent of year), "%j" stands for day of year:



                holidays <- format(as.Date(holidays), "%j")


                Generating some random data to test (1000 uniformly distributed work entries in 2017, 5 employees):



                d <- data.frame(
                'date' = as.Date(as.integer(runif(1000, 17167, 17531)), origin = '1970-01-01'),
                'emp' = sample(LETTERS[1:5], 1000, replace = T)
                )


                Filtering out the holidays:



                h <- d[format(d$date, "%j") %in% holidays, ]


                Counting number of holidays worked per employee using aggregate():



                aggregate(h$date, list(h$emp), length)

                # Group.1 x
                #1 A 3
                #2 B 4
                #3 C 2
                #4 D 5
                #5 E 1


                NB: will work for 2017, but won't work for leap years (one workaround that doesn't involve altering the code too too much is to change the year in the holiday vector manually).






                share|improve this answer












                Putting the holidays in a vector:



                holidays <- as.Date(c('2017-01-02', '2017-05-29', '2017-07-04', '2017-09-04', '2017-11-23', '2017-12-25'))


                Extracting month and day (to make it independent of year), "%j" stands for day of year:



                holidays <- format(as.Date(holidays), "%j")


                Generating some random data to test (1000 uniformly distributed work entries in 2017, 5 employees):



                d <- data.frame(
                'date' = as.Date(as.integer(runif(1000, 17167, 17531)), origin = '1970-01-01'),
                'emp' = sample(LETTERS[1:5], 1000, replace = T)
                )


                Filtering out the holidays:



                h <- d[format(d$date, "%j") %in% holidays, ]


                Counting number of holidays worked per employee using aggregate():



                aggregate(h$date, list(h$emp), length)

                # Group.1 x
                #1 A 3
                #2 B 4
                #3 C 2
                #4 D 5
                #5 E 1


                NB: will work for 2017, but won't work for leap years (one workaround that doesn't involve altering the code too too much is to change the year in the holiday vector manually).







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 13 '18 at 0:06









                12b345b6b7812b345b6b78

                767115




                767115



























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53271317%2fi-need-help-writing-a-function-to-count-the-number-of-holidays-within-a-time-per%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    這個網誌中的熱門文章

                    How to read a connectionString WITH PROVIDER in .NET Core?

                    In R, how to develop a multiplot heatmap.2 figure showing key labels successfully

                    Museum of Modern and Contemporary Art of Trento and Rovereto