[英]Is there a way to clean date and time data in r?
我试图总结从凌晨 4 点到下午 12 点的时间为早上,12-9 点为晚上,晚上 9 点到凌晨 4 点为晚上。 我这样做是为了制作一个逻辑回归模型,以了解是否会发生逮捕,而不会考虑犯罪类型和犯罪时间。
我曾尝试使用 lubridate 函数,但由于格式是字符串,我无法使用该函数。 而且, as.Date
函数也无济于事,因为某些字符串具有此值: 03/26/2015 06:56:30 PM
而某些行具有此值: 04-12-15 20:24
。 两种格式完全不同,因此无法使用as.Date
函数。
除了as.Date
函数,我们可以做的是将所有04-12-15 20:24
转换为04-12-15 20:24
03/26/2015 06:56:30 PM
格式,方法是 => 如果你找到-
然后用/
(用于日期格式)。
我不知道如何实现这个目标。
您可以使用case_when()
从dplyr
库来确定日期的格式,然后基于该格式类型的转换进行。 从那里我们检查 24H 时间组件以确定基于 OP 中的 bin 的时间。
library(dplyr)
chicago15 <- data.frame(Date = c("03/26/2015 06:56:30 PM","04-12-15 20:24",
"03/26/2015 06:56:30 AM","04-12-15 21:24",
"12/31/2017 03:28:43 AM"))
chicago15 %>%
dplyr::mutate(Date2 = dplyr::case_when(
grepl('-',Date) ~ as.POSIXct(Date,format = '%m-%d-%y %H:%M'),
TRUE ~ as.POSIXct(Date,format = '%m/%d/%Y %I:%M:%S %p')
)) %>%
dplyr::mutate(Time_of_Day = dplyr::case_when(
as.numeric(format(Date2,'%H')) >= 21 ~ 'night',
as.numeric(format(Date2,'%H')) >= 12 ~ 'evening',
as.numeric(format(Date2,'%H')) >= 4 ~ 'morning',
TRUE ~ 'night'
))
Date Date2 Time_of_Day
1 03/26/2015 06:56:30 PM 2015-03-26 18:56:30 evening
2 04-12-15 20:24 2015-04-12 20:24:00 evening
3 03/26/2015 06:56:30 AM 2015-03-26 06:56:30 morning
4 04-12-15 21:24 2015-04-12 21:24:00 night
5 12/31/2017 03:28:43 AM 2017-12-31 03:28:43 night
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.