R 基于时间的轮班日期
我试图根据时间限制按每个ID改变日期。例如,我需要添加一个单独的列作为Date Modified,它将把条目作为同一天添加到第二天早上5点。并在第二天发布参赛作品R 基于时间的轮班日期,r,datatable,dplyr,R,Datatable,Dplyr,我试图根据时间限制按每个ID改变日期。例如,我需要添加一个单独的列作为Date Modified,它将把条目作为同一天添加到第二天早上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 1346
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)))
使用
dplyr
和lubridate
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
数据
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))
df使用if_-else
而不是ifelse
@mauritservers:ifelse
将时间转换为数字,而if_-else
不转换,我认为它解决了OPs问题。基本R方法没有任何问题。然而,使用dplyr,我在parse_hms中遇到了错误。因此被转换成NA's@ssan您是否使用与所示相同的数据?实际上,base R和dplyr都在做同样的事情,所以我不确定是什么导致了这个错误。另外,我没有使用parse_hms
函数。在新的会话中尝试此操作,如果您仍然面临错误,是否可以发布数据的dput
dput(head(df))
转换时间格式似乎产生了错误。在我的数据中,时间字段是“字符”格式。这可能是一个原因吗?不应该是。您可以尝试我共享的数据的代码吗?这是否有效?您通过hm(df$time)获得什么输出
关于您的数据?它与您共享的数据配合良好。我认为可能的原因可能是我的数据格式。当我更改您数据中的格式时,我会收到相同的错误。
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))