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

将矩阵展开:为时间区间内的每一年生成对应行

问题:将事件时间区间展开为逐年记录

现有一个包含全球各国事件信息的R数据框,结构及示例如下:

a <- data.frame(country = c("AAA" , "BBB" , "CCC") ,
                incident = rep("disaster" , times = 3) ,
                'start year' = c(1990 , 1995 , 2011) ,
                'end year' = c(1993 , 1995 , 2012))

生成的数据框:

country incident start.year end.year
1     AAA disaster       1990     1993
2     BBB disaster       1995     1995
3     CCC disaster       2011     2012

需要将其转换为每行对应单个年份的事件记录,理想输出如下:

country incident year
1     AAA disaster 1990
2     AAA disaster 1991
3     AAA disaster 1992
4     AAA disaster 1993
5     BBB disaster 1995
6     CCC disaster 2011
7     CCC disaster 2012

最优解决方案

1. tidyverse 方案(易读性优先,适合常规数据)

利用dplyr和tidyr的组合,代码简洁易懂,适合多数日常数据处理场景:

library(tidyverse)

# 方法1:rowwise + unnest
a %>%
  rowwise() %>%
  mutate(year = list(start.year:end.year)) %>%
  unnest(year) %>%
  select(country, incident, year)

# 更高效的替代:reframe(无需rowwise)
a %>%
  reframe(
    year = start.year:end.year,
    .by = c(country, incident, start.year, end.year)
  ) %>%
  select(country, incident, year)

2. data.table 方案(性能优先,适合大数据)

如果数据量较大(如百万级以上),data.table的内存效率和运行速度优势明显:

library(data.table)

setDT(a)[, .(year = start.year:end.year), by = .(country, incident)]

两种方案都能精准生成目标结果,可根据数据规模和个人习惯选择。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 18:24:42