如何将xts格式月度时间序列转换为日度时间序列?
Hey there! I get exactly what you're trying to do—expand your monthly temperature data to daily values where every day in a month uses that month's temperature, keeping the monthly average intact. The to.period() function wasn't working because it's designed for aggregating higher-frequency data to lower frequencies (like daily to monthly), not the other way around. Let's fix this with a straightforward approach using zoo and xts tools you already have:
Step-by-Step Code Implementation
First, let's build on your existing code and add the expansion logic:
library("xts") library("zoo") # Ensure zoo is loaded since we're using its core functions # Your original data setup observation_dates <- as.Date(c("01.12.1993", "01.01.1994", "01.02.1994", "01.03.1994", "01.04.1994", "01.05.1994", "01.06.1994", "01.07.1994", "01.08.1994", "01.09.1994", "01.10.1994", "01.11.1994", "01.12.1994"), format = "%d.%m.%Y") air_data <- zoo(matrix(c(21, 21, 21, 30, 35.5, 36, 38.5, 33, 37, 37, 30, 24, 21), ncol = 1), observation_dates) colnames(air_data) = "air_temperature" # 1. Define the full daily date range we need # Start at the first month's day 1, end at the last month's final day start_date <- min(observation_dates) end_date <- as.Date(paste0(year(max(observation_dates)), "-", month(max(observation_dates)), "-01")) end_date <- seq(end_date, length.out = 2, by = "month")[2] - 1 # Get last day of the final month # 2. Create an empty daily time series daily_dates <- seq(start_date, end_date, by = "day") daily_series <- zoo(, order.by = daily_dates) # 3. Merge original monthly data with the empty daily series merged_data <- merge(daily_series, air_data, all = TRUE) # 4. Fill NA values with the last observed monthly value (forward fill) daily_air_data <- na.locf(merged_data)
How This Works
- Date Range: We calculate the full span from the first month's start to the last month's end, so we don't miss any days in between.
- Merge: Combining the empty daily series with your monthly data creates a series where only the first day of each month has a value, and all other days are
NA. - Forward Fill:
na.locf()(short for "last observation carried forward") fills everyNAwith the most recent non-NA value—this means every day in a month gets the month's temperature value, exactly what you need.
Verify the Result
You can check that the fill worked correctly by looking at a subset of days, like the last few days of December 1993:
# Check December 1993's final 5 days daily_air_data["1993-12-27/1993-12-31"]
This will return 21 for all those days, confirming the monthly value is applied to every day in the month.
内容的提问来源于stack exchange,提问作者Vasker Sharma

