首页 > 解决方案 > 使用 lubridate 包在 r 中创建 inteval 对象

问题描述

嗨,我有来自 uber 的数据: 在此处输入图像描述

关于纽约市的接送服务。我试图向原始数据添加一列,该列指示每一行,它属于哪个时间间隔(由时间间隔开始处的单个时间点表示)。

我想创建一个包含所有相关时间点的向量(即每 15 分钟在此向量上使用 lubridate 包中的 int_diff 函数来创建一个间隔对象。对原始数据中的所有时间点和每个数据点运行一个循环;指示它属于哪个间隔(由时间间隔开始处的单个时间点表示)。

我试图寻找解释如何使用 int_diff 函数,但我不明白我的向量应该如何看待以及 int_diff 的语法如何工作坦克寻求帮助:)

标签: rdatabasetimeintervalslubridate

解决方案


这是你的想法吗?

start <- mdy_hm('4/11/2014 0:00') # start of the period
end <- mdy_hm('5/12/2015 0:00') # end
time_seq <- seq(from = start, to = end, by = '15 mins') # sequence by 15 minutes

times <- mdy_hm(c('4/11/2014 0:12', '4/11/2014 1:24')) # times to find intervals for
dat <- data.frame(times)

dat$intervals <- cut(times, breaks = time_seq) # assign each time to an interval

intervals_cols <- model.matrix(~ - + intervals, dat) # turn this into a set of columns, one for each interval, with a 1 indicating that this observation falls into the column

推荐阅读