围绕干预聚合数据

问题描述 投票:0回答:1

我正在尝试跟踪干预前后的冲突数据。干预发生在特定日期,我想汇总干预前后 25 周内发生的冲突事件和伤亡人数。下表提供了名为“conflict_data”的数据示例。

我想将总和放入另一个数据集中以便稍后合并。类似这样,但有更多行的国家、年份和日期。另外,虽然为了简单起见,我只显示了干预前和干预后一周的情况,但我希望为干预日之前和之后 25 周的每一周提供专栏。我还省略了伤亡的示例,但理想情况下我希望将它们放在数据集中的同一行中。

这是我的代码。数据按天排列,但我按周汇总,因此我尝试每 7 天对冲突事件和伤亡人员进行求和(例如,第 1 周是第 1 天到第 7 天;第 2 周是第 8 天到第 7 天) 14;第 3 周是第 15 天到第 21 天,依此类推)。

# Function to indicate treatment days and aggregate data
aggregate_treatment_data <- function(df) {
  df %>%
    mutate(treatment = ifelse(!is.na(date.qualification), 1, 0)) %>%
    filter(treatment == 1) %>%
    group_by(country, year, day) %>%
    summarise(
      week1_pre_event_total = sum(conflict_event_count[(which(treatment == 1) - 7):(which(treatment == 1) - 1)], na.rm = TRUE),
      week1_pre_casualties = sum(sum_casualties[(which(treatment == 1) - 7):(which(treatment == 1) - 1)], na.rm = TRUE)
    )
}

# Create a new conflict dataset with aggregated data for 1 week before the treatment
conflict_data_aggregated <- aggregate_treatment_data(conflict_data)

当我输入它时,conflict_data_aggreated 数据集只返回 0。这是它的截图:

我再次计划稍后将每周总和与另一个数据集合并。任何有关如何围绕干预措施按周汇总金额的建议都会令人惊叹。我为我的胡言乱语道歉。如果有任何不清楚的地方,请随时问我。预先感谢您!

r aggregate
1个回答
0
投票

这就是我相信您正在寻找的东西。如果没有,请发表评论,或将其用作实现所需输出的起点:

library(tidyverse)

set.seed(0)

df <- data.frame(
    country = rep(c("Applonia", "Banania", "Cocovia"), each = (52*7) + 1),
    conflict_events = sample(0:100, 3 * ((52*7) + 1), replace = TRUE),
    deaths = sample(0:100, 3 * ((52*7) + 1), replace = TRUE),
    intervention = (26*7) + 1)
new_df <- df |> mutate(day = rep(1:((52*7) + 1), 3),
             week = ifelse(intervention > day, floor((day - intervention) /7),  ceiling((day - intervention) /7)))
new_df |> 
  summarise(across(c(conflict_events, deaths), \(x) sum(x, na.rm = TRUE)), .by = c(country, week)) |>
  pivot_wider(names_from = week, values_from = c(conflict_events, deaths))

输出:

# A tibble: 3 × 107
  country  `conflict_events_-26` `conflict_events_-25` `conflict_events_-24`
  <chr>                    <int>                 <int>                 <int>
1 Applonia                   279                   402                   402
2 Banania                    298                   359                   491
3 Cocovia                    364                   279                   385
# ℹ 103 more variables: `conflict_events_-23` <int>,
#   `conflict_events_-22` <int>, `conflict_events_-21` <int>,
#   `conflict_events_-20` <int>, `conflict_events_-19` <int>,
#   `conflict_events_-18` <int>, `conflict_events_-17` <int>,
#   `conflict_events_-16` <int>, `conflict_events_-15` <int>,
#   `conflict_events_-14` <int>, `conflict_events_-13` <int>,
#   `conflict_events_-12` <int>, `conflict_events_-11` <int>, …
# ℹ Use `colnames()` to see all variable names
© www.soinside.com 2019 - 2024. All rights reserved.