在 R 中将工作日转换为日期

问题描述 投票:0回答:2

我有这样的数据:

sample_data <- c("Sun 11.30am", "Tues 01.00pm", "Mon 10.00am", "Sun 01.30am", "Thurs, 02.30pm")

我想根据工作日返回年/月/日/时间,假设工作日是当天的下一次出现(所需数据基于我发布此问题的日期,即 3 月 17 日星期五):

desired_data <- c("2023-03-19 11:30AM", "2023-03-21 01:00PM", "2023-03-20 10:00AM","2023-03-19 01:30AM","2023-03-23 02:30PM")

是否有一个简单的 R 函数可以做到这一点?谢谢!

r date datetime weekday
2个回答
1
投票
library(lubridate)

start_date <- as.Date("2023-03-17")

lapply(sample_data, function(x) {
  res <- start_date
  wday(res, week_start = wday(start_date) - 1) <- stringr::str_extract(x, "^[:alpha:]+")
  time_of_the_day <- parse_date_time(x, "%H %M %p")
  hour(res) <- hour(time_of_the_day)
  minute(res) <- minute(time_of_the_day)
  res
})
[[1]]
[1] "2023-03-19 11:30:00 UTC"

[[2]]
[1] "2023-03-21 13:00:00 UTC"

[[3]]
[1] "2023-03-20 10:00:00 UTC"

[[4]]
[1] "2023-03-19 01:30:00 UTC"

[[5]]
[1] "2023-03-23 14:30:00 UTC"

0
投票
sample_data <- c("Sun 11.30am", "Tues 01.00pm", "Mon 10.00am", "Sun 01.30am", "Thurs, 02.30pm")

today <- Sys.Date()
today_weekday <- as.numeric(format(today, "%u"))
day <- tolower(substr(sample_data, 1, 3))
day_diff <- match(day, c("mon", "tue", "wed", "thu", "fri", "sat", "sun"))
dayR <- today + ((day_diff + 7) - today_weekday) %% 7
dayR
#[1] "2023-03-19" "2023-03-21" "2023-03-20" "2023-03-19" "2023-03-23"

time <- substr(sample_data, nchar(sample_data) - 6, nchar(sample_data))
time
#[1] "11.30am" "01.00pm" "10.00am" "01.30am" "02.30pm"

final <- as.POSIXct(paste(dayR, time), format = "%Y-%m-%d %H.%M%p")
final_formatted <- format(final, "%Y-%m-%d %H:%M%p")
final_formatted
#[1] "2023-03-19 11:30AM" "2023-03-21 01:00AM" "2023-03-20 10:00AM" "2023-03-19 01:30AM" "2023-03-23 02:30AM"
© www.soinside.com 2019 - 2024. All rights reserved.