使用dplyr和lubridate按时分筛选每日9:00-20:15时段数据
Hey there! I get that you've already dug into filtering by hour alone, but need to narrow it down to a specific daily time window (9:00 AM to 8:15 PM) regardless of the date. Let's tackle this with dplyr and lubridate—here are two reliable approaches that'll get you what you need:
Step 1: Ensure Your Timestamp is a Datetime Type
First up, make sure your timestamp column is formatted as a datetime object (not a plain character string). For your example data (month/day/year hour:minute format), use lubridate's mdy_hm() function to convert it:
library(dplyr) library(lubridate) # Convert timestamp from character to datetime df <- df %>% mutate(timestamp = mdy_hm(timestamp))
Step 2: Filter for the Target Time Window
Approach 1: Compare Pure Time Values (Simplest)
Use hms::as_hms() to strip away the date component and get just the time portion of your datetime. Then compare this directly to your start and end times:
df_filtered <- df %>% filter( hms::as_hms(timestamp) >= hms::as_hms("09:00:00"), hms::as_hms(timestamp) <= hms::as_hms("20:15:00") )
This method is clean and straightforward—since we're only comparing the time part, it works seamlessly across all dates in your dataset.
Approach 2: Break Down Hour & Minute (More Flexible)
If you need more control (like adjusting minute thresholds later), use lubridate's hour() and minute() functions to build explicit logical conditions:
df_filtered <- df %>% filter( # Keep times after 9:00 AM (hour(timestamp) > 9) | (hour(timestamp) == 9 & minute(timestamp) >= 0) | # AND keep times before/at 8:15 PM (hour(timestamp) < 20) | (hour(timestamp) == 20 & minute(timestamp) <= 15) )
This logic clearly checks:
- Any time after 9 AM, or exactly 9 AM and beyond the 0th minute
- Any time before 8 PM, or exactly 8 PM and up to the 15th minute
Verify the Result
For your sample data, the filtered output will exclude the 8:45 AM entry and keep all rows from 9:00 AM onward (up to 20:15 PM if those times exist in your full dataset).
内容的提问来源于stack exchange,提问作者longlivebrew

