R: How to get the Week number of the month

前端 未结 9 842
孤街浪徒
孤街浪徒 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:46

    I don't know any build in functions but a work around would be

    CurrentDate <- Sys.Date()
    # The number of the week relative to the year
    weeknum <- as.integer( format(CurrentDate, format="%U") )
    
    # Find the minimum week of the month relative to the year
    mindatemonth <- as.Date( paste0(format(CurrentDate, "%Y-%m"), "-01") )
    weeknummin <- as.integer( format(mindatemonth, format="%U") ) # the number of the week of the first week within the month
    
    # Calculate the number of the week relative to the month
    weeknum <- weeknum - (weeknummin - 1) # this is as an integer
    
    # With the following you can convert the integer to the same format of 
    # format(CurrentDate, format="%U")
    formatC(weeknum, width = 2, flag = "0")
    

提交回复
热议问题