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

R语言计算另一数据框同公园事件发生前的反应事件总数

问题解决方法

错误原因

你现有代码的核心问题出在summarize步骤的计数逻辑完全错误:

  1. 你提前执行了filter(Date <= Month)过滤,剩余行已经全部满足Date早于等于Month的条件,但后续计数用的条件Month <= Date & Month >= Date等价于要求Date和Month完全相等,和你要统计「所有早于等于Month的事件数」的需求不符,因此返回结果全为0。
  2. 提前filter的操作会删除没有匹配反应记录的报告行,导致最终输出丢失原数据中的行。
  3. 额外注意:需先确保Date和Month两列均为R的日期格式,避免字符串比较逻辑异常。

修复后可运行代码

第一步:统一日期格式

library(dplyr)
# 转换两表的日期列为标准Date类型
Reaction_per_park_per_day_3 <- Reaction_per_park_per_day_3 %>%
  mutate(Date = as.Date(Date))
Reports_per_park_per_day_3 <- Reports_per_park_per_day_3 %>%
  mutate(Month = as.Date(Month))

第二步:计算Number_AC列

提供两种实现方案:

方案1:基于左连接逻辑修正(适合数据量不大的场景)

Reports_per_park_per_day_3 <- Reports_per_park_per_day_3 %>%
  left_join(Reaction_per_park_per_day_3, by = "Park") %>%
  group_by(Park, Month) %>%
  # 直接统计符合Date<=Month的行数,无匹配时返回0
  summarise(Number_AC = sum(Date <= Month, na.rm = TRUE), .groups = "drop")

方案2:逐行计算(逻辑更直观)

Reports_per_park_per_day_3 <- Reports_per_park_per_day_3 %>%
  rowwise() %>%
  mutate(
    Number_AC = sum(
      Reaction_per_park_per_day_3$Park == Park & 
      Reaction_per_park_per_day_3$Date <= Month
    )
  ) %>%
  ungroup()

两种方案运行后均可得到你给出的预期结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 21:54:06