lubridate添加新列以添加每周的小时

4c8rllxm  于 2023-01-15  发布在  其他
关注(0)|答案(1)|浏览(181)

我有这个数据框

city                 date           
London  2022-01-01 00:00:00     
London  2022-01-01 01:00:00      
London  2022-01-01 02:00:00
London  2022-01-01 03:00:00
London  2022-01-01 04:00:00
London  2022-01-01 05:00:00
London  2022-01-01 06:00:00
...
London  2022-01-07 00:00:00
...
Glasgow 2022-01-01 00:00:00
Glasgow 2022-01-01 00:00:00
Glasgow 2022-01-01 00:00:00
...

我想按城市分组,并添加新的列称为每周小时。
它显示;

city                 date         hour of the week               
London  2022-01-01 00:00:00               0
London  2022-01-01 01:00:00               1   
London  2022-01-01 02:00:00               2
London  2022-01-01 03:00:00               3
London  2022-01-01 04:00:00               4
London  2022-01-01 05:00:00               5
London  2022-01-01 06:00:00               6
...
London  2022-01-07 23:00:00             167
...
Glasgow 2022-01-01 00:00:00               0
Glasgow 2022-01-01 01:00:00               1
Glasgow 2022-01-01 02:00:00               2
...

我试过了([天-1] * 24 +小时的腹肌)这工作,但我想知道是否有一种方法来做它与lubridate.我已经检查了有作为.持续时间,但我不能设法使它的工作.

t98cgbkg

t98cgbkg1#

我们可以

library(dplyr)
library(lubridate)
df1 %>%
    mutate(date = ymd_hms(date), 
      hour_of_the_week = (day(date)-1) * 24 + hour(date))

相关问题