如何将日期格式化为日期名称+周数

时间:2019-12-09 15:50:20

标签: r date

我想将日期格式设置为WEEK NUMBER IN CURRENT MONTH + DAYNAME。换句话说,今天-“ 2019-12-09”将为2 - Monday

我创建了此代码

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 ~ "?")

但是说实话,我不知道如何处理星期数

1 个答案:

答案 0 :(得分:0)

lubridate中有一个week函数可以给出一年中的星期。

我在下面创建了一个函数。

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"