在R中以X个小时为单位舍入时间? [英] Round time by X hours in R?

查看:90
本文介绍了在R中以X个小时为单位舍入时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在对带时间戳的数据进行预测建模时,我想在R中编写一个函数(可能使用data.table),该函数将日期四舍五入为X小时。例如。四小时取整应为:

While doing predicting modeling on timestamped data, I want to write a function in R (possibly using data.table) that rounds the date by X number of hours. E.g. rounding by 2 hours should give this:

"2014-12-28 22:59:00 EDT" becomes "2014-12-28 22:00:00 EDT" 
"2014-12-28 23:01:00 EDT" becomes "2014-12-29 00:00:00 EDT" 

当您舍入1小时时,这非常容易-使用 round.POSIXt(.date, hour)函数。

编写通用函数,就像我在下面使用多个 if 语句所做的一样,但是变得很难看: / p>

It's very easy to do when you round by 1 hour - using round.POSIXt(.date, "hour") function.
Writing a generic function, like I'm doing below using multiple if statements, becomes quite ugly however:

d7.dateRoundByHour <- function (.date, byHours) { 

  if (byHours == 1)
    return (round.POSIXt(.date, "hour"))

  hh = hour(.date); dd = mday(.date); mm = month(.date); yy = year(.date)    
  hh = round(hh/byHours,digits=0) * byHours
  if (hh>=24) { 
    hh=0; dd=dd+1 
  }
  if ((mm==2 & dd==28) | 
      (mm %in% c(1,3,5,7,8,10,12) & dd==31) | 
      (mm %in% c(2,4,6,9,11) & dd==30)) {  # NB: it won't work on 29 Feb leap year. 
    dd=1; mm=mm+1
  }
  if (mm==13) {
    mm=1; yy=yy+1
  }
  str = sprintf("%i-%02.0f-%02.0f %02.0f:%02.0f:%02.0f EDT", yy,mm,dd, hh,0,0)
  as.POSIXct(str, format="%Y-%m-%d %H:%M:%S") 
}

任何人都可以显示一种更好的方法吗?

(也许通过转换为数字回到POSIXt或其他POSIXt函数?)

Anyone can show a better way to do that?
(perhaps by converting to numeric and back to POSIXt or some other POSIXt functions?)

推荐答案

使用 round_date lubridate软件包中的函数。假设您有一个data.table,其中的列名为date,则可以执行以下操作:

Use the round_date function from the lubridate package. Assuming you had a data.table with a column named date you could do the following:

dt[, date := round_date(date, '2 hours')]

一个简单的示例将为您提供所需的准确结果:

A quick example will give you exactly the results you were looking for:

x <- as.POSIXct("2014-12-28 22:59:00 EDT")
round_date(x, '2 hours')

这篇关于在R中以X个小时为单位舍入时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆