在R中如何对时间列分箱、统计响应数并用ggplot2可视化?
Hey there! Let's break down your two time-binning questions in R clearly, with practical code examples tailored to your needs.
Creating time bins in R boils down to grouping timestamps into consistent time intervals, and there are two main approaches depending on your workflow:
Using the lubridate package (tidyverse-friendly)
The lubridate package makes time manipulation intuitive. For common bin sizes, use these functions:
- Floor to the start of the interval:
floor_date(datetime, "interval")— e.g.,floor_date(my_datetime, "hour")will round 15:40 down to 15:00, fitting it into the 15:00-16:00 bin. - Ceiling to the end of the interval:
ceiling_date(datetime, "interval")— e.g., 15:40 becomes 16:00, placing it in the 15:00-16:00 bin but labeled by the end time. - Round to the nearest interval:
round_date(datetime, "interval")
You can use custom intervals too, like 30-minute bins: floor_date(datetime, "30 minutes").
Using base R's cut.POSIXt
If you prefer base R, use cut() with POSIXct datetime objects:
# For hourly bins my_data$hour_bin <- cut(my_data$datetime, breaks = "hour") # For 1-day bins my_data$day_bin <- cut(my_data$datetime, breaks = "day")
Note: If your time data is split into separate date and time columns, first combine them into a single POSIXct datetime column (we'll cover this in Problem 2).
Let's walk through this step-by-step using your sample dataframe, with tidyverse and ggplot2 for a clean workflow.
Step 1: Prepare your data
First, we'll combine the separate date and time columns into a proper datetime format, then create our hourly bins. We'll use lubridate to parse dates/times easily.
# Load required packages library(tidyverse) library(lubridate) # Create your sample dataframe df <- tibble( date = c("1/1/2018", "4/5/2017", "3/4/2016", "5/4/2017"), time = c("15:40", "08:25", "09:00", "09:25"), respond = c(1, 0, 1, 1) ) # Combine date + time into a POSIXct datetime column df <- df %>% mutate(datetime = dmy_hm(str_c(date, time, sep = " "))) # Create hourly bins (08:00-09:00 → labeled as 08:00) df <- df %>% mutate(hour_bin = floor_date(datetime, "hour"))
Step 2: Count responses per time bin
Since your respond column uses 1s and 0s, summing the values gives the total number of responses per bin. We'll also format the bin labels to be more readable for visualization.
hourly_response_summary <- df %>% group_by(hour_bin) %>% summarise(total_responses = sum(respond)) %>% # Format bin as "HH:00" string (e.g., 2017-04-05 08:00:00 → "08:00") mutate(hour_label = format(hour_bin, "%H:00"))
Step 3: Visualize with ggplot2
Now we'll plot the hourly response counts with a bar chart, making it easy to spot trends.
ggplot(hourly_response_summary, aes(x = hour_label, y = total_responses)) + # Bar chart with a clean color geom_col(fill = "#2E86AB", alpha = 0.8) + # Add labels and title labs( title = "Total Responses by Hourly Time Bin", x = "Time Bin", y = "Number of Responses" ) + # Clean theme with rotated x-axis labels for readability theme_minimal() + theme(axis.text.x = element_text(angle = 45, hjust = 1))
This will give you a clear bar chart showing how many responses fall into each hourly bin.
内容的提问来源于stack exchange,提问作者steves

