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

如何将双时间点宽格式数据转换为含步长1全时间点的长格式?

如何将宽格式数据转换为长格式,同时包含步长为1的所有时间点?

需求说明

原始数据为宽格式,每条记录包含唯一id、起始时间time1和结束时间time2,需要把每个id对应的从time1到time2的所有连续时间点(步长为1)拆分成单独行,转换为长格式数据。

模拟数据

library(tidyverse)

df = tibble(
  id = c("a", "b", "c", "d", "e", "f"),
  time1 = c(0,1,2,3,4,5),
  time2 = c(3,2,6,7,5,9))

出错的解决方案

df %>% 
  mutate(
  timepoint = str_c(seq(time1, time2, 1), ",", collapse ="")) %>%   
  separate_rows(timepoint, sep = ",")

执行这段代码后,所有id的时间点会被错误合并成一个全局字符串,拆分后无法对应到各自的id,结果不符合预期。

正确解决方案

方法一:rowwise() + unnest()

通过rowwise()让每行单独处理,生成对应时间序列的列表,再用unnest()展开成多行:

df %>%
  rowwise() %>%
  mutate(timepoint = list(seq(time1, time2, 1))) %>%
  unnest(timepoint)

方法二:map2() + unnest()

利用purrr的map2()函数,逐行对time1和time2生成时间序列,再展开:

df %>%
  mutate(timepoint = map2(time1, time2, seq, by = 1)) %>%
  unnest(timepoint)

错误原因解析

原代码里str_c(..., collapse = "")的collapse参数会把所有行生成的时间序列字符串合并成一个整体,而非每行单独生成自己的时间点字符串,最终导致separate_rows拆分后,时间点无法和原id正确匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 05:05:26