根据时间调整日期

时间:2019-11-26 10:28:04

标签: r datatable dplyr

我正在尝试根据时间限制按每个ID更改日期。例如,我需要添加一个单独的列作为“修改日期”,该列将在同一天输入直到第二天凌晨5点。条目将被视为第二天。

 ID     Date and Time   Date         Time   Date Modified
13462   9/4/2019 15:38  9/4/2019    15:38   9/4/2019
13462   9/4/2019 20:23  9/4/2019    20:23   9/4/2019
13462   9/4/2019 23:23  9/4/2019    23:23   9/4/2019
13462   9/5/2019 4:23   9/5/2019    4:23    9/4/2019
13462   9/5/2019 7:23   9/5/2019    7:23    9/5/2019

当我尝试根据日期和数字来添加日期+ 1时。希望有一些建议。

df1%>%
  group_by(ID)%>%
  mutate(Date_Modified = ifelse(format(Date and Time,"%H:%M:%S")>="05:00:00",as.Date(Date)+1,as.Date(Date)))

1 个答案:

答案 0 :(得分:0)

使用dplyrlubridate

library(dplyr)
library(lubridate)

df %>%
 mutate(Date = mdy(Date),
        mod_Date = if_else(hour(hm(Time)) < 5, Date - 1, Date))

#     ID Date_and_Time       Date  Time Date_Modified   mod_Date
#1 13462 9/4/201915:38 2019-09-04 15:38      9/4/2019 2019-09-04
#2 13462 9/4/201920:23 2019-09-04 20:23      9/4/2019 2019-09-04
#3 13462 9/4/201923:23 2019-09-04 23:23      9/4/2019 2019-09-04
#4 13462  9/5/20194:23 2019-09-05  4:23      9/4/2019 2019-09-04
#5 13462  9/5/20197:23 2019-09-05  7:23      9/5/2019 2019-09-05

我也不认为您不需要group_by ID,因为这里没有按组进行计算。


使用基数R

df$Date <- as.Date(df$Date, "%m/%d/%Y")
inds <- as.integer(format(as.POSIXct(df$Time, format = "%H:%M"), "%H")) < 5
df$Mod_date <- df$Date
df$Mod_date[inds] <- df$Date[inds] - 1

数据

df <- structure(list(ID = c(13462L, 13462L, 13462L, 13462L, 13462L), 
Date_and_Time = structure(1:5, .Label = c("9/4/201915:38", 
"9/4/201920:23", "9/4/201923:23", "9/5/20194:23", "9/5/20197:23"
), class = "factor"), Date = structure(c(1L, 1L, 1L, 2L, 
2L), .Label = c("9/4/2019", "9/5/2019"), class = "factor"), 
Time = structure(1:5, .Label = c("15:38", "20:23", "23:23", 
"4:23", "7:23"), class = "factor"), Date_Modified = structure(c(1L, 
1L, 1L, 1L, 2L), .Label = c("9/4/2019", "9/5/2019"), class = "factor")), 
class = "data.frame", row.names = c(NA, -5L))