Ian.T
Ian.T

Reputation: 1166

Find the first day of the x week of the x year

Is there a way to find the first day of the x week of the x year with the package lubridate?

For example I have this data: week number in some year (e.g 33th week from the year 1988) and i would like to convert it into a data like: day/month/year (e.g 15/08/1988).

Missing_day <- c("33/1988", "37/1991", "37/1992", 
             "41/1994", "15/1997", "18/2001", 
             "50/2001", "16/2002", "35/2004", 
             "5/2012", "50/2012", "8/2013", 
             "36/2013", "51/2017")

thanks

Upvotes: 0

Views: 67

Answers (2)

Ray
Ray

Reputation: 471

Do note the discussion here about:

  1. Specifying the day of the week
  2. Ensuring you understand the different ways in which R enumerates weeks of a year
library(dplyr)
library(stringr)
# Using Lubridate per your request
library(lubridate)
tibble(week_year = Missing_day) %>%
  mutate(
    day_month_year = format(lubridate::parse_date_time(
      paste(
        str_extract(string = week_year, pattern = "^\\d+"),
        str_extract(string = week_year, pattern = "\\d*$"),
        'Mon',
        sep =
          "/"
      ), 'W/Y/a'
    ), "%d/%m/%Y")
  )

# A tibble: 14 x 2
# week_year  day_month_year
#    <chr>        <chr>         
# 1 33/1988    15/08/1988    
# 2 37/1991    16/09/1991    
# 3 37/1992    14/09/1992    
# 4 41/1994    10/10/1994    
# 5 15/1997    14/04/1997    
# 6 18/2001    30/04/2001    
# 7 50/2001    10/12/2001    
# 8 16/2002    22/04/2002    
# 9 35/2004    30/08/2004    
# 10 5/2012    30/01/2012    
# 11 50/2012   10/12/2012    
# 12 8/2013    25/02/2013    
# 13 36/2013   09/09/2013    
# 14 51/2017   18/12/2017 
# Using Base R
tibble(week_year = Missing_day) %>%
  mutate(
    day_month_year = format(as.Date(
      paste(
        1,
        str_extract(string = week_year, pattern = "^\\d+"),
        str_extract(string = week_year, pattern = "\\d*$"),
        sep = "/"
      ), "%w/%W/%Y"
    ), "%d/%m/%Y")
  )

# A tibble: 14 x 2
# week_year  day_month_year
#    <chr>       <chr>         
# 1 33/1988    15/08/1988    
# 2 37/1991    16/09/1991    
# 3 37/1992    14/09/1992    
# 4 41/1994    10/10/1994    
# 5 15/1997    14/04/1997    
# 6 18/2001    30/04/2001    
# 7 50/2001    10/12/2001    
# 8 16/2002    22/04/2002    
# 9 35/2004    30/08/2004    
# 10 5/2012    30/01/2012    
# 11 50/2012   10/12/2012    
# 12 8/2013    25/02/2013    
# 13 36/2013   09/09/2013    
# 14 51/2017   18/12/2017 

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389325

You can attach the weekday and convert the data into Date. Using base R, you can do :

as.Date(paste0('1/', Missing_day), '%u/%U/%Y')

# [1] "1988-08-15" "1991-09-16" "1992-09-14" "1994-10-10" "1997-04-14"
# [6] "2001-05-07" "2001-12-17" "2002-04-22" "2004-08-30" "2012-01-30"
#[11] "2012-12-10" "2013-02-25" "2013-09-09" "2017-12-18"

Upvotes: 1

Related Questions