如何将日度数据重复24次合并至小时时间序列数据集?
Hey there! Let's figure out how to merge your daily and hourly datasets properly. Based on the head() output you shared, I'm assuming you're working in R—here are two simple, reliable approaches to get your desired DF8 structure:
Method 1: Using Tidyverse (dplyr + tidyr)
This is a clean, readable way to handle the duplication and merge:
- First, make sure both datasets have a consistent date column (same name and data type)
- Duplicate each daily record 24 times (once per hour)
- Merge the expanded daily data with your hourly dataset
library(tidyverse) # Clean up DF1: standardize date column name and format DF1_clean <- DF1 %>% rename(date = Date) %>% mutate(date = as.Date(date)) # Expand daily data to hourly: repeat each row 24 times DF1_hourly <- DF1_clean %>% mutate(repeat_count = 24) %>% uncount(repeat_count) # Merge with DF5 (ensure DF5's date is also a Date type) DF8 <- DF5 %>% mutate(date = as.Date(date)) %>% left_join(DF1_hourly, by = "date")
Method 2: Base R (No External Packages)
If you prefer sticking to base R, this works just as well:
# Standardize date columns in both datasets DF1$date <- as.Date(DF1$Date) DF5$date <- as.Date(DF5$date) # Repeat each row in DF1 24 times DF1_hourly <- DF1[rep(seq_len(nrow(DF1)), each = 24), c("date", "Coalprice")] # Merge with DF5, keeping all hourly rows DF8 <- merge(DF5, DF1_hourly, by = "date", all.x = TRUE)
Quick Check Tip
Before merging, it's a good idea to verify that every date in DF5 has exactly 24 hourly entries. You can do this with:
# For tidyverse users DF5 %>% count(date) %>% filter(n != 24) # For base R users table(DF5$date)
This will flag any dates with missing or extra hourly rows, so you can clean those up first if needed.
内容的提问来源于stack exchange,提问作者S. Jay
相关产品推荐
相关产品推荐

