如何用lubridate为按城市分组的DataFrame添加周小时列?
问题描述
我有如下DataFrame:
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分组,添加名为hour of the week的新列,结果如下:
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 ...
我试过用公式([day-1] * 24 + hour)可以实现,但想知道怎么用lubridate包来完成,之前尝试as.duration没成功。
解决方案
可以结合lubridate的日期时间函数和dplyr的分组操作实现,核心是计算每条记录与分组内最早时间的小时差:
library(dplyr) library(lubridate) df <- df %>% group_by(city) %>% mutate( # 确保date列为datetime格式,若已转换可省略 date = ymd_hms(date), # 计算当前时间与分组最早时间的小时间隔 `hour of the week` = as.duration(date - min(date)) %/% hours(1) ) %>% ungroup()
关键步骤说明:
group_by(city):按城市分组,保证每个城市的时间计算独立进行ymd_hms(date):将字符型日期转换为lubridate可识别的datetime格式date - min(date):得到当前时间与分组内最早时间的时间间隔as.duration(...) %/% hours(1):将间隔转为时长后除以1小时,得到从0开始递增的小时数
也可以用interval和int_length函数实现相同效果:
df <- df %>% group_by(city) %>% mutate( date = ymd_hms(date), `hour of the week` = int_length(interval(min(date), date)) / 3600 ) %>% ungroup()
这里int_length返回间隔的秒数,除以3600直接得到小时数。
内容的提问来源于stack exchange,提问作者Dome
相关产品推荐
相关产品推荐

