I'm trying to calculate the number of weeks and weekdays between two dates?
for example from 2017-01-01
, 2018-01-01
, number of Monday in months and year and number of week
Here are some suggestions for the number of Mondays in the whole time span and in each month. I am not sure how you mean to calculate the number of weeks. Is it different than Days/7?
Notice that I included 2018-01-01 in the time period.
library(lubridate)
#>
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#>
#> date, intersect, setdiff, union
Dates <- seq.Date(from = ymd("2017-01-01"), to = ymd("2018-01-01"), by = 1)
#Number of Mondays
sum(wday(Dates) == 2)
#> [1] 53
#Days of week per month (January has 6 Mondays because Jan. 1 2018 is a Monday)
table(month(Dates), wday(Dates))
#>
#> 1 2 3 4 5 6 7
#> 1 5 6 5 4 4 4 4
#> 2 4 4 4 4 4 4 4
#> 3 4 4 4 5 5 5 4
#> 4 5 4 4 4 4 4 5
#> 5 4 5 5 5 4 4 4
#> 6 4 4 4 4 5 5 4
#> 7 5 5 4 4 4 4 5
#> 8 4 4 5 5 5 4 4
#> 9 4 4 4 4 4 5 5
#> 10 5 5 5 4 4 4 4
#> 11 4 4 4 5 5 4 4
#> 12 5 4 4 4 4 5 5
Created on 2020-04-28 by the reprex package (v0.3.0)
1 Like
Thanks @FJCC
why when I using name day instead of number day it gives me zero!
sum(wday(Dates, label =T) == "Monday")
[1] 0
Try
sum(wday(Dates, label = TRUE) == "Mon")
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.