Number of Weeks in a month

How can we get number of weeks form a Date.

Example
2022 Jan 5 weeks
2022 Feb 4 weeks

Thanks!

# Example Data 
# Looking to add Number of Weeks Column next to Date using mutate. But not sure, how to achieve the number of weeks in a given month.

df <- data.frame(
  Date = c("2018 Jan","2018 Jan","2018 Jan","2018 Jan",
           "2018 Feb","2018 Feb","2018 Feb","2018 Feb"))

df$Date <- ym(df$Date)

the answer to this question must depend on what a week is; what does it mean that January 2022 has 5 weeks...
Its surely not that it has 7*5=35 days. do you want to count the mondays ? or are you looking to find how many times 7 days goes into each month, which in january is 31/7 = 4.428571 (which does not round up to 5)

If you go for the non-rounding option in Nirgrahamuk's answer, an approach could be to take the last day of the month, and compute the difference in weeks:

last_day <- function(d){
  month(d) <- month(d) + 1
  d - ddays(1)
}

difftime(last_day(df$Date[[1]]),
         df$Date[[1]],
         units = "weeks")
#> Time difference of 4.285714 weeks

to get info on num weeks by simple division, for all months, you can do

lubridate::days_in_month(1:12)/7

giving

     Jan      Feb      Mar      Apr      May      Jun      Jul      Aug      Sep      Oct      Nov      Dec 
4.428571 4.000000 4.428571 4.285714 4.428571 4.285714 4.428571 4.428571 4.285714 4.428571 4.285714 4.428571
2 Likes

Thanks @nirgrahamuk & @AlexisW !
These options work great. I will just consider anything more than 4.4 as 5 weeks for now and 4 weeks otherwise.

But this is helpful. Thank you both!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.