【问题标题】:Stacking time series data vertically垂直堆叠时间序列数据
【发布时间】:2016-10-27 08:34:03
【问题描述】:

我正在努力处理时间序列数据。数据集的第一列包含有关数据收集时间点的信息,第二列以后包含来自不同研究的数据。我有数百项研究。作为一个例子,我已经包含了 5 项研究的样本数据。我想将数据集与每个研究的时间和数据点垂直堆叠。示例数据集如下所示:

TIME    Study1  Study2  Study3  Study4  Study5
0.00    52.12   53.66   52.03   50.36   51.34
90.00   49.49   51.71   49.49   48.48   50.19
180.00  47.00   49.83   47.07   46.67   49.05
270.00  44.63   48.02   44.77   44.93   47.95
360.00  42.38   46.28   42.59   43.25   46.87
450.00  40.24   44.60   40.50   41.64   45.81
540.00  38.21   42.98   38.53   40.08   44.78

我正在寻找以下形式的输出:

TIME    Study   ID
0   52.12   1
90  49.49   1
180 47  1
270 44.63   1
360 42.38   1
450 40.24   1
540 38.21   1
0   53.66   2
90  51.71   2
180 49.83   2
270 48.02   2
360 46.28   2
450 44.6    2
540 42.98   2
0   52.03   3
90  49.49   3
180 47.07   3
270 44.77   3
...

【问题讨论】:

  • 使用来自tidyrgatherdf %>% gather(ID, Study, -TIME)

标签: r time-series


【解决方案1】:

这是一个经典的“从宽到长”的数据集操作。下面,我展示了base 函数?reshape 对您的数据的使用:

d.l <- reshape(d, varying=list(c("Study1","Study2","Study3","Study4","Study5")),
               v.names="Y", idvar="TIME", times=1:5, timevar="Study",
               direction="long")
d.l <- d.l[,c(2,1,3)]
rownames(d.l) <- NULL
d.l
#    Study TIME     Y
# 1      1    0 52.12
# 2      1   90 49.49
# 3      1  180 47.00
# 4      1  270 44.63
# 5      1  360 42.38
# 6      1  450 40.24
# 7      1  540 38.21
# 8      2    0 53.66
# 9      2   90 51.71
# 10     2  180 49.83
# 11     2  270 48.02
# 12     2  360 46.28
# 13     2  450 44.60
# 14     2  540 42.98
# 15     3    0 52.03
# 16     3   90 49.49
# 17     3  180 47.07
# ...

但是,在 R 中有很多方法可以做到这一点:关于 SO 的最基本参考(这可能是重复的)是 Reshaping data.frame from wide to long format,但还有许多其他相关线程(请参阅此搜索:[r] wide to long )。除了使用reshape,还可以使用@lmo 的方法,以及基于reshape2tidyrdata.table 包的方法(可能还有其他)。

【讨论】:

    【解决方案2】:

    这是使用cbindstack 的一种方法:

     longdf <- cbind(df$TIME, stack(df[,-1], ))
     names(longdf) <- c("TIME", "Study", "id")
    

    返回

    longdf
       TIME Study     id
    1     0 52.12 Study1
    2    90 49.49 Study1
    3   180 47.00 Study1
    4   270 44.63 Study1
    5   360 42.38 Study1
    6   450 40.24 Study1
    7   540 38.21 Study1
    8     0 53.66 Study2
    9    90 51.71 Study2
    ...
    

    如果您想将 id 更改为示例中的整数,请使用

    longdf$id <- as.integer(longdf$id)
    

    【讨论】:

    • 感谢您的回复和您的宝贵时间!