【问题标题】:Analyse day-time of a date-time variable分析日期时间变量的白天时间
【发布时间】:2016-05-13 06:54:41
【问题描述】:

这就是我解决问题的方法:

datestimes <- c("2014-01-01 23:03:00", "2014-01-02 00:35:00", "2014-01-02 00:51:00") # There is a change in date. 
# Is there any lubridate command for the following step?    
time <- as.POSIXct(strftime(datetimes, format = "%H:%M:%S", tz = "UTC"), format = "%H:%M:%S") 
time  
[1] "2016-05-13 23:03:00 CEST" "2016-05-13 00:35:00 CEST" "2016-05-13 00:51:00 CEST"

lubridate 中没有这样的功能是否有原因? 正如我所说 - 我只对时间部分感兴趣 - 而不是日期。

lubridate::hms 给出句号:

ltime <- lubridate::hms(strftime(datetimes, format = "%H:%M:%S", tz = "UTC"))  
ltime  
[1] "23H 3M 0S" "35M 0S"    "51M 0S"  
class(ltime)  
[1] "Period"  
attr(,"package")  
[1] "lubridate"

【问题讨论】:

  • 您能否更清楚地描述您的问题?没有日期的时间并没有很好地定义,因为会有 DST 甚至偶尔的闰秒等不便之处。
  • lubridate 没有没有日期的时间类(除了句点,虽然你可以工作,但有点不同)。您可以查看chron
  • Well lubridate 可以提取小时、分钟、秒。您也可以使用正则表达式来获取时间组件。
  • 我猜你可以用 ymd_hms(paste(today(), format(ymd_hms(datetimes), '%T'))) 做同样的事情......但我不确定这是一个很好的方法。
  • @Roland:假设datetimes 是瞬间,电影院大楼里的人都算在内。现在你要分析,人们什么时候去电影院,取决于白天的时间。你有比 alistaire 更好的主意吗? @alistaire:你的方法似乎完全符合我的需要——而且它告诉你用today覆盖日期是准确的。

标签: r lubridate


【解决方案1】:

这个怎么样?

library(lubridate)
datetimes <- c("2014-01-01 23:03:00", "2014-01-02 00:35:00", "2014-01-02 00:51:00") 
dataset <- data.frame(
  time = as.POSIXct(strftime(datetimes, format = "%H:%M:%S", tz = "UTC"), format = "%H:%M:%S") 
)
dataset$delta <- dataset$time - floor_date(dataset$time, unit = "day")
dataset$relative <- as.POSIXct("2001-01-01 0:0:0") + minutes(dataset$delta)

library(ggplot2)
ggplot(dataset, aes(x = relative)) + 
  geom_histogram(binwidth = 3600) + 
  scale_x_datetime(date_breaks = "3 hour", date_labels = "%H:%M")

【讨论】:

  • alistaire 方法的优点是,您有可用的小时和分钟(和秒)。因此,您可以得到一个简单而漂亮的brks &lt;- trunc(range(time), "hours") + hist(time, breaks = seq(brks[1], brks[2] + 3600, by = "15 min"), freq = T) 形式的直方图。分辨率为 1 小时或 30 分钟的绘图也很容易获得。
  • 我已经使用了我的答案。 ggplot2 有很多选项来格式化日期时间类。
  • 除了+ scale_x_datetime(date_breaks = "3 hour", date_labels = "%H:%M") 行之外的所有东西都可以:Error in continuous_scale(aesthetics, "datetime", identity, breaks = breaks, : unused arguments (date_breaks = "3 hour", date_labels = "%H:%M") 我刚刚拿走了你的代码。
  • 它可以在我的机器上使用 R 3.3.0,ggplot2 2.1.0,比例 0.4.0,lubridate 1.5.6。检查您是否拥有最新版本的软件包。
  • 是的:-) +1 将我指向 ggplot2 以及它是如何在这里工作的。我仍然认为你使用这个技巧来覆盖日期 - 这里 alistaire 的方式对我来说是最清楚的。
【解决方案2】:

感谢 alistair:ymd_hms(paste(today(), format(ymd_hms(datetimes), '%T'))) 将是我的选择。这可以很好地与histggplot2 结合使用(见上文)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-18
    • 2012-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-29
    • 1970-01-01
    相关资源
    最近更新 更多