为何无法基于时间范围筛选数据集?求技术排查方案
问题:筛选共享单车数据集中1-2月数据时日期解析失败
从Kaggle下载了共享单车需求数据集,希望在分析中仅保留1月至2月的数据。
数据集结构
structure(list(datetime = c("1/20/2011 0:00", "1/20/2011 1:00", "1/20/2011 2:00", "1/20/2011 3:00", "1/20/2011 4:00", "1/20/2011 5:00" ), season = c(1, 1, 1, 1, 1, 1), holiday = c(0, 0, 0, 0, 0, 0 ), workingday = c(1, 1, 1, 1, 1, 1), weather = c(1, 1, 1, 1, 1, 1), temp = c(10.66, 10.66, 10.66, 10.66, 10.66, 9.84), atemp = c(11.365, 13.635, 13.635, 12.88, 12.88, 11.365), humidity = c(56, 56, 56, 56, 56, 60), windspeed = c(26.0027, 0, 0, 11.0014, 11.0014, 15.0013 )), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"))
尝试的筛选代码
已安装Lubridate和Tidyverse包,使用以下代码筛选:
test %>% filter(as_date(datetime) >= as_date("2011-01-20") & as_date(datetime) <= as_date("2011-02-20"))
运行错误
出现警告:
Warning messages:
1: All formats failed to parse. No formats found.
解决方案
问题根源是as_date()无法自动识别你的日期字符串格式(MM/DD/YYYY HH:MM),不需要重新上传数据,只需指定正确的解析格式即可:
方法1:分步转换+筛选
library(lubridate) library(tidyverse) # 转换datetime列为datetime类型 test_clean <- test %>% mutate(datetime = mdy_hm(datetime)) # 筛选指定日期范围的数据 test_filtered <- test_clean %>% filter(date(datetime) >= ymd("2011-01-20") & date(datetime) <= ymd("2011-02-20"))
方法2:一步完成
test %>% mutate(datetime = mdy_hm(datetime)) %>% filter(date(datetime) between(ymd("2011-01-20"), ymd("2011-02-20")))
关键说明
mdy_hm()是lubridate专门处理月/日/年 时:分格式的函数,能精准匹配你的日期字符串,避免自动解析失败date()函数从datetime类型中提取纯日期部分,方便进行日期范围筛选between()函数可以简化区间条件的写法,让代码更简洁
内容的提问来源于stack exchange,提问作者Geoffrey Archer
相关产品推荐
相关产品推荐

