0

I'd like to format my dates as WEEK NUMBER IN CURRENT MONTH + DAYNAME. In other words, today - "2019-12-09" would be 2 - Monday

I created this code

day_name <- format(Sys.Date(), "%w")

day30_name <- 
case_when (
  day_name == 1 ~ "Monday",
  day_name == 2 ~ "Tuesday",
  day_name == 3 ~ "Wednesday",
  day_name == 4 ~ "Thursday",
  day_name == 5 ~ "Friday",
  day_name == 6 ~ "Saturday",
  day_name == 0 ~ "Sunday",
  TRUE ~ "?")

But honestly I have no idea how to deal with week number

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 1
    Wouldn't `weekdays(Sys.Date())` works – akrun Dec 09 '19 at 15:53
  • 1
    Check this out https://stackoverflow.com/questions/25199851/r-how-to-get-the-week-number-of-the-month – ThomasIsCoding Dec 09 '19 at 16:06
  • 1
    You should look at the docs for `strftime` which has a list of all the format options. You've used `%w`, which returns the number of the day of the week. `%A` would give you the name of the day of the week; for week number there are several options depending on locale – camille Dec 09 '19 at 17:11
  • 1
    There are 7 answers for day name [here](https://stackoverflow.com/q/9216138/5325862) and 8 for week number [here](https://stackoverflow.com/q/22439540/5325862). Does the combination of those two posts not cover it? – camille Dec 09 '19 at 17:15

1 Answers1

0

There is a week function in lubridate that gives week of the year.

I've created a function below.

WeekNum_DayName <- function(x) {

    week_month_start <- week(floor_date(x, 'month')) # week number of first of the month
    week_num <- week(x) - week_month_start + 1 # week number from month start
    day_name <- as.character(wday(x, label = TRUE, abbr = FALSE))
    str_c(week_num, day_name, sep = ' - ') # combine them
}

x <- ISOdate(year=2019, month=12, day=9, hour = 12, min = 0, sec = 0, tz = "GMT")
WeekNum_DayName(x)

#[1] "2 - Monday"

x <- as.Date('2019-01-01')
WeekNum_DayName(x)

#[1] "1 - Tuesday"
Tony Ladson
  • 3,539
  • 1
  • 23
  • 30