R语言:使用complete函数补全缺失月份时生成重复条目问题
解决补全缺失月份时生成重复条目的问题
原代码的核心问题
- 日期序列生成错误:
seq(min(date), Sys.Date(), by = 1)按天生成序列,导致每个月产生几十条重复条目,后续的summarize(n())错误地统计了天数而非月份数。 - 分组字段错误:使用了不存在的
City_Name字段,应该是原始数据中的City。 - 未按城市分组补全:补全年份时没有先按
City分组,导致跨城市生成重复的日期条目。
修正后的代码
library(tidyverse) library(lubridate) # 转换原始数据的日期格式 data <- data %>% mutate(date = mdy(date)) # 定义当前日期(示例中为2023-04-02) current_date <- ymd("2023-04-02") # 计算6个月范围的起始和结束月份(包含当前月) start_month <- floor_date(current_date %m-% months(5), "month") end_month <- floor_date(current_date, "month") # 聚合+补全缺失月份 months6 <- data %>% # 筛选出6个月范围内的记录 filter(date >= start_month) %>% # 将日期转换为当月第一天,用于分组 mutate(ym = floor_date(date, "month")) %>% # 按城市+月份聚合,统计记录数 group_by(City, ym) %>% summarize(Total_city = n(), .groups = "drop") %>% # 按城市分组,补全所有缺失的月份,缺失值填0 group_by(City) %>% complete(ym = seq(start_month, end_month, by = "1 month"), fill = list(Total_city = 0)) %>% # 转换为期望的日期格式(mm/yyyy) mutate(date = format(ym, "%m/%Y")) %>% # 选择需要的字段 select(City, date, Total_city) %>% ungroup() # 查看LA的结果 filter(months6, City == "LA")
输出结果(LA部分)
# A tibble: 6 × 3 City date Total_city <chr> <chr> <int> 1 LA 11/2022 1 2 LA 12/2022 2 3 LA 01/2023 2 4 LA 02/2023 0 5 LA 03/2023 0 6 LA 04/2023 0
内容的提问来源于stack exchange,提问作者akang
相关产品推荐
相关产品推荐

