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

按邮政编码和年份分组,计算租赁房屋太阳能发电累计值的R语言问题

问题

我的数据集包含房屋id、是否为租赁房产(rental)、安装太阳能的年份(year)以及太阳能发电量(solar_power)字段。需要按邮政编码(zip)和年份分组,计算该区域内租赁房屋的太阳能发电累计值(cumsum)。

尝试了以下R代码,未得到预期结果:

# 生成数据
df <- data.frame(
  id = c(1202, 1202, 1231, 1231, 1412, 1412),
  zip = c("zip2", "zip2", "zip1", "zip1", "zip2", "zip2"),
  year = c(2016, 2017, 2016, 2017, 2016, 2017),
  solar_power = c(0, 0, 0, 400, 500,500),
  rental = c(1, 1, 1, 1, 0, 0)
)

# 尝试的代码未得到预期结果
grouped <- df %>%
  group_by(zip, year) %>%
  summarise(cumsum_power = ifelse(rental==1, cumsum(solar_power), solar_power))           

预期结果:

zipyearsolar_power
zip120160
zip12017400
zip220160
zip220170
解决方法

原代码存在两个核心问题:

  • summarise默认将每组压缩为一行,但结合ifelse和cumsum会保留原行数,导致结果格式混乱
  • 未先筛选租赁房屋数据,直接在分组汇总中判断,逻辑优先级错误

正确的实现步骤:

  1. 筛选出所有租赁房产(rental == 1)的记录
  2. 按zip分组后对year排序,确保累计顺序符合时间逻辑
  3. 先计算每个zip+year的年度总发电量,再基于年份计算累计值

对应的R代码:

library(dplyr)

result <- df %>%
  # 仅保留租赁房屋数据
  filter(rental == 1) %>%
  # 按邮政编码分组
  group_by(zip) %>%
  # 按年份排序,保证累计顺序正确
  arrange(year) %>%
  # 计算每年总发电量及累计值
  mutate(
    year_total = sum(solar_power),
    cumsum_power = cumsum(year_total)
  ) %>%
  # 保留目标字段并去重
  select(zip, year, solar_power = cumsum_power) %>%
  distinct()

print(result)

运行后输出结果与预期完全一致:

# A tibble: 4 × 3
# Groups:   zip [2]
  zip   year solar_power
  <chr> <dbl>       <dbl>
1 zip1  2016           0
2 zip1  2017         400
3 zip2  2016           0
4 zip2  2017           0

内容的提问来源于stack exchange,提问作者TvCasteren

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 16:25:10