R: How to get the Week number of the month

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

    By analogy of the weekdays function:

    monthweeks <- function(x) {
        UseMethod("monthweeks")
    }
    monthweeks.Date <- function(x) {
        ceiling(as.numeric(format(x, "%d")) / 7)
    }
    monthweeks.POSIXlt <- function(x) {
        ceiling(as.numeric(format(x, "%d")) / 7)
    }
    monthweeks.character <- function(x) {
        ceiling(as.numeric(format(as.Date(x), "%d")) / 7)
    }
    dates <- sample(seq(as.Date("2000-01-01"), as.Date("2015-01-01"), "days"), 7)
    dates
    #> [1] "2004-09-24" "2002-11-21" "2011-08-13" "2008-09-23" "2000-08-10" "2007-09-10" "2013-04-16"
    monthweeks(dates)
    #> [1] 4 3 2 4 2 2 3
    

    Another solution to use stri_datetime_fields() from the stringi package:

    stringi::stri_datetime_fields(dates)$WeekOfMonth
    #> [1] 4 4 2 4 2 3 3
    

提交回复
热议问题