R语言中从dttm类型列提取小时失败,求正确实现方法
R语言中从dttm类型列提取小时失败,求正确实现方法
嘿,我来帮你捋捋问题出在哪~你现在得到全00的结果,是因为as.Date()这个函数会把带时间的dttm类型转换成只保留日期的Date类型,自动丢掉了小时、分钟这些时间信息,所以再用format()提取小时自然只能拿到00啦。
给你几个简单好用的解决办法,选你顺手的来:
方法1:直接用format()处理原dttm列
不用多此一举转成Date类型,直接对started_at这个dttm列用format()提取小时就行:
biketimes2$time <- format(biketimes2$started_at, "%H")
这样就能得到你想要的两位数字格式的小时(比如23、08、18)。
方法2:用lubridate包的hour()函数(推荐)
如果平时经常要处理时间数据,lubridate包会帮你省超多事,它专门针对时间类型做了简化:
先安装并加载包(没装过的话):
install.packages("lubridate") library(lubridate)
然后提取小时,默认是数值类型(比如23、8、18),如果想要两位字符格式,再加一步转换:
# 得到数值类型的小时 biketimes2$time_num <- hour(biketimes2$started_at) # 得到两位字符格式的小时 biketimes2$time_char <- sprintf("%02d", hour(biketimes2$started_at))
方法3:用strftime()函数
和format()功能类似,也能直接处理dttm列:
biketimes2$time <- strftime(biketimes2$started_at, "%H")
你先试试第一种方法,应该就能拿到正确的小时结果啦~
附你提供的原数据结果参考:
head(biketimes2) # A tibble: 6 × 6 started_at date month day_of_week days time <dttm> <date> <chr> <chr> <chr> <chr> 1 2022-05-23 23:06:58 2022-05-23 05 Monday 23 00 2 2022-05-11 08:53:28 2022-05-11 05 Wednesday 11 00 3 2022-05-26 18:36:28 2022-05-26 05 Thursday 26 00 4 2022-05-10 07:30:07 2022-05-10 05 Tuesday 10 00 5 2022-05-10 17:31:56 2022-05-10 05 Tuesday 10 00 6 2022-05-04 14:48:55 2022-05-04 05 Wednesday 04 00
备注:内容来源于stack exchange,提问作者Lucy K
相关产品推荐
相关产品推荐

