You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于门店开业闭店日期的年度门店数量统计(R语言)

R语言实现城镇年末门店数量统计(循环版)

实现思路

针对大数据量场景,通过双重循环遍历城镇和年份,结合日期判断统计符合条件的门店数,同时采用预分配结果空间的方式提升效率。

完整代码

# 加载日期处理包
library(lubridate)

# 原始数据
town <- c("A", "A", "A", "B")
opening <- as.Date(c("1900-01-01", "1905-02-05", "1906-01-01", "1910-01-01"))
closing <- as.Date(c(NA, NA, NA, "1913-03-03"))
df <- data.frame(town, opening, closing)

# 定义需要统计的年份范围(与示例一致,可根据数据自动调整)
target_years <- 1900:1905
# 获取所有唯一城镇
unique_towns <- unique(df$town)

# 预分配结果数据框(大数据量下避免频繁rbind的性能损耗)
total_rows <- length(unique_towns) * length(target_years)
df_final <- data.frame(
  town_final = character(total_rows),
  year = integer(total_rows),
  stores = integer(total_rows),
  stringsAsFactors = FALSE
)

row_idx <- 1

# 双重循环统计
for (t in unique_towns) {
  # 筛选当前城镇的门店数据
  town_data <- df[df$town == t, ]
  
  for (y in target_years) {
    # 生成当年年末日期(12月31日)
    year_end <- make_date(y, 12, 31)
    
    # 统计符合条件的门店数:开业≤年末,且(闭店>年末 或 闭店未记录)
    store_count <- sum(
      town_data$opening <= year_end & 
        (is.na(town_data$closing) | town_data$closing > year_end),
      na.rm = TRUE
    )
    
    # 写入结果
    df_final[row_idx, ] <- list(t, y, store_count)
    row_idx <- row_idx + 1
  }
}

# 查看最终结果
print(df_final)

代码说明

  • 预分配空间:提前计算结果数据框的行数,避免循环中反复rbind导致的性能下降,适合大数据量场景。
  • 日期判断逻辑:门店需满足两个条件才算年末在营:
    1. 开业日期 ≤ 当年12月31日
    2. 闭店日期 > 当年12月31日,或闭店日期为NA(表示门店仍在营业)
  • 灵活调整年份范围:如果需要自动匹配数据中的年份区间,可替换target_years为:
    all_years <- c(year(df$opening), year(df$closing[!is.na(df$closing)]))
    target_years <- min(all_years):max(all_years)
    

内容的提问来源于stack exchange,提问作者L.P. Hayek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 02:00:37