将R中的日期四舍五入为任意分钟/小时的精度 [英] round a date in R to an arbitrary minute/hour level of precision
问题描述
我希望以任意精度将R中的日期分组.
I'm looking to group dates in R by an arbitrary level of precision.
使用例如 lubridate
:
library(lubridate)
nearest_hour = floor_date(now(), 'hour')
然后,您可以将此类日期的列表分组,例如来自 plyr
的简单 summary
ddply
.
You can then group a list of such dates with e.g. a simple summarise
ddply
from plyr
.
我想做的是以任意精度对日期进行舍入,例如到最近的15分钟或每3个小时一次:
What I'd like to do is round dates with arbitrary precision, e.g. to the nearest 15 minutes or every 3 hours:
nearest_three_hours = floor_date(now(), '3 hours')
There's a discussion of such things at http://r.789695.n4.nabble.com/Truncating-dates-and-other-date-time-manipulations-td866901.html but outside of cutting dates, there doesn't appear to have been any resolution.
推荐答案
将已经地板的润滑到最近的原子单元.为了使发言权最接近15分钟(我认为这是您想要做的(而不是四舍五入)),您只需要通过findInterval和一组定义的断点映射到正确的范围即可.试试这个floor_time,它在功能上等同于floor_date,但是允许您为秒,分钟或小时指定可变的单位数.
lubridate already floors to the nearest atomic unit. To get floor to the nearest 15 minutes, which I think is what you want to do (not round), you just need to map into the correct range via findInterval and a defined set of breakpoints. Try this floor_time, which is functionally equivalent to floor_date, but allows you to specify a variable # of units for seconds, minutes or hours.
floor_time <- function(x, k = 1, unit = c("second", "minute", "hour", "day",
"week", "month", "year")) {
require(lubridate)
nmax <- NULL
switch(unit, second = {nmax <- 60},
minute = {nmax <- 60},
hour = {nmax <- 24})
cuts <- seq(from = 0, to = nmax - 1, by = k)
new <- switch(unit,
second = update(x, seconds = cuts[findInterval(second(x), cuts)]),
minute = update(x, minutes = cuts[findInterval(minute(x), cuts)],
seconds = 0),
hour = update(x, hours = cuts[findInterval(hour(x), cuts)],
minutes = 0, seconds = 0),
day = update(x, hours = 0, minutes = 0, seconds = 0),
week = update(x, wdays = 1, hours = 0, minutes = 0, seconds = 0),
month = update(x, mdays = 1, hours = 0, minutes = 0, seconds = 0),
year = update(x, ydays = 1, hours = 0, minutes = 0, seconds = 0))
new
}
这篇关于将R中的日期四舍五入为任意分钟/小时的精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!