【问题标题】:Cut timestamp into numeric slots in R将时间戳切割成R中的数字槽
【发布时间】:2017-02-18 16:39:49
【问题描述】:

我有时间戳列,数据格式为2016-01-01 00:41:23

我想从整个数据集中将这些数据转换为 12 个插槽,每个插槽 2 小时。数据不重要,只需要考虑时间。

00:00:00 - 01:59:59 - slot1
02:00:00 - 03:59:59 - slot2
.......
22:00:00 - 23:59:59 - slot12

如何在 R 中实现这一点?

x <- c("01:59:59", "03:59:59", "05:59:59",
   "07:59:59", "09:59:59", "11:59:59",
   "13:59:59", "15:59:59", "17:59:59",
   "19:59:59", "21:59:59", "23:59:59")

cut(pickup_time, breaks = x)

上面的代码给出错误::'x'必须是数字

【问题讨论】:

  • 您想将此数据帧转换为 12 个不同数据帧的列表吗?
  • 我想在现有数据集中添加一列以及 slotnumber

标签: r timestamp


【解决方案1】:

将您的数据框视为df,我们可以使用cutbreaks 2 小时。

df$slotnumber <- cut(strptime(df$x, "%H:%M:%S"), breaks = "2 hours", 
                                                labels = paste0("slot", 1:12))

#      x       slotnumber
#1  01:59:59      slot1
#2  03:59:59      slot2
#3  05:59:59      slot3
#4  07:59:59      slot4
#5  09:59:59      slot5
#6  11:59:59      slot6
#7  13:59:59      slot7
#8  15:59:59      slot8
#9  17:59:59      slot9
#10 19:59:59     slot10
#11 21:59:59     slot11
#12 23:59:59     slot12

数据

df <- data.frame(x)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-10
    • 1970-01-01
    • 1970-01-01
    • 2020-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-14
    相关资源
    最近更新 更多