-1

I am trying to create a "Week" column in my data and cannot figure out how to correctly assign the first day of the first week (starting on Sunday, December 30, 2018) to Week 1 of 2019.

12/30/2018 was a Sunday and I want to assign it to the first day of Week 1 for 2019; after searching online for too long, I figured I should just ask it on here.

If you need more clarity:

    DATE             DAY       WEEK
    12/30/2018    Sunday         01  (first day of week 1)
    12/31/2018    Monday         01
    1/01/2019    Tuesday         01
    .                  .          .
    .                  .          .
    .                  .          .
    1/6/2019      Sunday         02  (the first day of week 2)
    .                  .          .
    .                  .          .
    .                  .          .
    .                  .          .
    .                  .          .
    .                  .          .
6/26/2019         Sunday         22 (first day of week 22)
    .                  .          .
    .                  .          .
    .                  .          .
jrolfe
  • 25
  • 4

2 Answers2

1

lubridate package has functions for these.

#Using Ronak's Data
library(lubridate)
epiweek(mdy(df$DATE))
#[1]  1  1  1  2 26

You can get more info by typing ?lubridate::week

d.b
  • 32,245
  • 6
  • 36
  • 77
0

Convert to date and then use format and adjust to get expected output

library(dplyr)
df %>%
  mutate(DATE = as.Date(DATE, "%m/%d/%Y"), 
         wk = (as.integer(format(DATE, "%U")) + 1) %% 52)

#        DATE     DAY wk
#1 2018-12-30  Sunday  1
#2 2018-12-31  Monday  1
#3 2019-01-01 Tuesday  1
#4 2019-01-06  Sunday  2
#5 2019-06-26  Sunday 26

data

df <- structure(list(DATE = structure(c(3L, 4L, 1L, 2L, 5L), .Label = c("1/01/2019", 
"1/6/2019", "12/30/2018", "12/31/2018", "6/26/2019"), class = "factor"), 
DAY = structure(c(2L, 1L, 3L, 2L, 2L), .Label = c("Monday", 
"Sunday", "Tuesday"), class = "factor")), class = "data.frame", 
row.names = c(NA, -5L))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213