我有一列连续的时间(小时、分钟、秒(,间隔不相等,持续了好几天。
例如:
library(lubridate)
df <- data.frame(Data = c(1:10),
Time = hms(c("10:00:00","15:38:44","22:12:37",
"23:59:00","00:07:28","04:56:00",
"08:01:25","12:10:54","16:08:43",
"20:44:44")))
我想创建一个包含日期和时间的新列,假设第一个数据点是在2020年1月1日10:00:00获取的。因此,例如,数据点8将得到"0";2020年1月2日12:10:54";。
我解决这个问题的尝试不值得在这里发布,有人有什么建议吗?
非常感谢!
这有点棘手,但这里有一个解决方案:
require(tidyverse)
require(lubridate)
dataf <- tibble(Data = c(1:16),
Time = hms(c("10:00:00","15:38:44","22:12:37",
"23:59:00","00:07:28","04:56:00",
"08:01:25","12:10:54","16:08:43",
"20:44:44","00:07:28","04:56:00",
"08:01:25","12:10:54","16:08:43",
"20:44:44")))
dataf_2 <- dataf %>%
mutate(Data = Data + 1,
Time_n = as.numeric(Time)) %>%
select(Data, Time_n)
dataf %>%
left_join(dataf_2, by = c("Data")) %>%
replace_na(list(Time_n = 0)) %>%
mutate(starting_date = dmy("01/01/2020")) %>%
mutate(change_day = if_else(as.numeric(Time) >= Time_n, 0, 1)) %>%
arrange(Data) %>%
mutate(cumsum=cumsum(change_day),
t = paste(hour(Time), minute(Time), second(Time))) %>%
mutate(final_date = ymd_hms(paste(starting_date + days(cumsum), t))) %>%
select(Data, Time, final_date)
它将产生这样的输出:
# A tibble: 16 x 3
Data Time final_date
<dbl> <Period> <dttm>
1 1 10H 0M 0S 2020-01-01 10:00:00
2 2 15H 38M 44S 2020-01-01 15:38:44
3 3 22H 12M 37S 2020-01-01 22:12:37
4 4 23H 59M 0S 2020-01-01 23:59:00
5 5 7M 28S 2020-01-02 00:07:28
6 6 4H 56M 0S 2020-01-02 04:56:00
7 7 8H 1M 25S 2020-01-02 08:01:25
8 8 12H 10M 54S 2020-01-02 12:10:54
9 9 16H 8M 43S 2020-01-02 16:08:43
10 10 20H 44M 44S 2020-01-02 20:44:44
这应该有效:
df %>%
mutate(
lag = lag(Time),
diff = Time - lag,
add_days = if_else(is.na(diff), 0, if_else(diff < 0, 1, 0)),
add_days_cum = cumsum(add_days),
date = ymd("2020-01-01") + days(add_days_cum) + Time
)