如何将R中的数据帧分成30分钟的桶

时间:2014-02-25 08:11:01

标签: r

我的数据框包含时间,格式为2014-01-31 15:33:50。

我正在尝试编写一个逻辑,将整天分解为30分钟的桶,以便我可以运行一些统计测试。

你能否告诉我如何通过R。

来完成

1 个答案:

答案 0 :(得分:3)

尝试类似:

start <- as.POSIXct("2012-01-15")
end <- start + as.difftime(1, units="mins")
Time.DF <- data.frame(Time = seq(from=start, by=15, to=end),
                      Info = 1:5)
# This is one way to do it
Time.DF$Bins <- with(Time.DF, {cut(
  Time, breaks = seq(from=min(Time), by=30, to=max(Time + 30)), labels = F)})
#                     Time Info Bins
# 1 2012-01-15 00:00:00    1    1
# 2 2012-01-15 00:00:15    2    1
# 3 2012-01-15 00:00:30    3    2
# 4 2012-01-15 00:00:45    4    2
# 5 2012-01-15 00:01:00    5    3

# This is a second way to do it
Time.DF$Bins2 <- with(Time.DF, {as.numeric(cut(
  Time, breaks = seq(from=min(Time), by=30, to=max(Time + 30))))})
#                     Time Info Bins Bins2
# 1 2012-01-15 00:00:00    1    1     1
# 2 2012-01-15 00:00:15    2    1     1
# 3 2012-01-15 00:00:30    3    2     2
# 4 2012-01-15 00:00:45    4    2     2
# 5 2012-01-15 00:01:00    5    3     3