R: How to get the Week number of the month

前端 未结 9 845
孤街浪徒
孤街浪徒 2020-11-30 04:05

I am new in R.
I want the week number of the month, which the date belongs to.

By using the following code:

>CurrentDate<-Sys.Date()
>We         


        
9条回答
  •  感情败类
    2020-11-30 04:56

    Using lubridate you can do

    ceiling((day(date) + first_day_of_month_wday(date) - 1) / 7)
    

    Where the function first_day_of_month_wday returns the weekday of the first day of month.

    first_day_of_month_wday <- function(dx) {
      day(dx) <- 1
      wday(dx)
    }
    

    This adjustment must be done in order to get the correct week number otherwise if you have the 7th day of month on a Monday you will get 1 instead of 2, for example. This is only a shift in the day of month. The minus 1 is necessary because when the first day of month is sunday the adjustment is not needed, and the others weekdays follow this rule.

提交回复
热议问题