【问题标题】:Shift date based on the time根据时间移动日期
【发布时间】:2019-11-26 10:28:04
【问题描述】:

我正在尝试根据时间限制按每个 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)))

【问题讨论】:

  • 使用if_else 而不是ifelse
  • @MauritsEvers:ifelse 将时间转换为数字,而 if_else 没有,我认为它解决了 OP 的问题。

标签: r datatable dplyr


【解决方案1】:

使用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_byID,因为这里没有按组进行计算。


使用基础 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))

【讨论】:

  • 我没有遇到基本 R 方法的任何问题。但是,使用 dplyr 我在 parse_hms 中遇到错误。因此被转换为 NA 的
  • @ssan 您使用的数据与显示的相同吗?实际上,base R 和dplyr 正在做同样的事情,所以我不确定是什么导致了这个错误。另外我没有使用parse_hms 函数。在新会话中尝试此操作,如果您仍然遇到错误,您可以发布您的数据的dput 吗? dput(head(df))
  • 看起来转换时间格式会产生错误。在我的数据中,时间字段是“字符”格式。这可能是原因吗?
  • 不应该。你能试试我分享的数据的代码吗?那样有用吗 ? hm(df$Time) 对您的数据有什么输出?
  • 它可以很好地处理您共享的数据。我认为可能的原因可能是我的数据格式。当我更改您的数据格式时,我遇到了同样的错误。
猜你喜欢
  • 2013-04-21
  • 1970-01-01
  • 1970-01-01
  • 2016-04-15
  • 2022-01-03
  • 2016-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多