将 "Y-m-w" 转换为日期 - 一周的第一个星期一
Transform "Y-m-w" to date - first Monday of the week
我正在尝试将 %Y-%m-%w
转换为从星期一开始的相应周的第一个日期。
所以 %Y-%m-%w
到 %Y-%m-%d
x <- c("2020-09-01", "2020-09-03", "2020-09-04", "2020-09-05")
2020-09-01 -> 2020-08-31
2020-09-03 -> 2020-09-14
2020-09-04 -> 2020-09-21
2020-09-05 -> 2020-09-28
使用 lubridate,转换为忽略周数的日期,因此所有日期都从 1 日开始。然后加上周数,最后四舍五入到星期一。
library(lubridate)
x <- c("2020-09-01", "2020-09-03", "2020-09-04", "2020-09-05")
x1 <- ymd(paste0(substring(x, 1, 8), "01"))
# [1] "2020-09-01" "2020-09-01" "2020-09-01" "2020-09-01"
x2 <- as.numeric(substring(x, 9, 10)) - 1
# [1] 0 2 3 4
x3 <- x1 + weeks(x2)
# [1] "2020-09-01" "2020-09-15" "2020-09-22" "2020-09-29"
floor_date(x3, unit = "weeks", week_start = 1) #1 represents Monday.
# [1] "2020-08-31" "2020-09-14" "2020-09-21" "2020-09-28"
我正在尝试将 %Y-%m-%w
转换为从星期一开始的相应周的第一个日期。
所以 %Y-%m-%w
到 %Y-%m-%d
x <- c("2020-09-01", "2020-09-03", "2020-09-04", "2020-09-05")
2020-09-01 -> 2020-08-31
2020-09-03 -> 2020-09-14
2020-09-04 -> 2020-09-21
2020-09-05 -> 2020-09-28
使用 lubridate,转换为忽略周数的日期,因此所有日期都从 1 日开始。然后加上周数,最后四舍五入到星期一。
library(lubridate)
x <- c("2020-09-01", "2020-09-03", "2020-09-04", "2020-09-05")
x1 <- ymd(paste0(substring(x, 1, 8), "01"))
# [1] "2020-09-01" "2020-09-01" "2020-09-01" "2020-09-01"
x2 <- as.numeric(substring(x, 9, 10)) - 1
# [1] 0 2 3 4
x3 <- x1 + weeks(x2)
# [1] "2020-09-01" "2020-09-15" "2020-09-22" "2020-09-29"
floor_date(x3, unit = "weeks", week_start = 1) #1 represents Monday.
# [1] "2020-08-31" "2020-09-14" "2020-09-21" "2020-09-28"