Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Custom calendar week number

Suppose I have a calendar that goes from April-April. Using R, how do I find out which week number (e.g. 1-52) a date belongs to?

Here is some data:

example_df <- data.frame(
    full_date = as.Date(c("2020-04-01", "2020-04-08", "2021-03-25", "2021-04-02"))
)

I thought of this way which pushes all dates back to January and then recalculates:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    library(lubridate)
    

example_df %>%
  mutate(
    date_obj = as.Date(full_date),
    fiscal_year = ifelse(month(date_obj) < 4, year(date_obj) - 1, year(date_obj)),
    fiscal_year_start = as.Date(paste0(fiscal_year, "-04-01")),
    days_since_fy_start = as.numeric(date_obj - fiscal_year_start),
    fiscal_week = ceiling((days_since_fy_start + 1) / 7)
  )

Is there another way to do this in R?


    get_april_year <- function(dates) {
      dates <- as.Date(dates)
      
      calendar_year <- as.numeric(format(dates, "%Y"))
      month <- as.numeric(format(dates, "%m"))
      
    
      start_year <- ifelse(month < 4, calendar_year - 1, calendar_year)
      
      fiscal_year <- paste0(start_year, "-", start_year + 1)
      
      return(fiscal_year)
    }

test_dates <- as.Date(c("2020-06-02", "2025-02-15", "2020-04-01"))
get_april_year (test_dates)

>Solution :

Update

Now I got your point that you want to start the "year" from a given date, then probably you could use

> as.integer(full_date - full_date[1]) %/% 7 + 1
[1]  1  2 52 53

Previous

You can use %V to present the week number

> full_date <- as.Date(c("2020-04-01", "2020-04-08", "2021-03-25", "2021-04-02"))

> format(full_date, "%V")
[1] "14" "15" "12" "13"

If you type ?strptime, you will see other similar options, e.g., %U and %W, which depends on what you really need.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading