制作时间序列数据

时间:2019-05-29 05:22:24

标签: r

我有一个如下所示的时间序列观测数据框

 Year/Month APR MAY JUN.......MAR
    2012     201 203 208...   2016
    2013     220 221 222......2018
    2014      ....................
     .        .
     .        .
     .        .
    2019      230 235 237      240

我需要这样的数据

 Period      Value
Apr-2012      .
May-2012      .  
Jun-2012      .
.
.
.
.
.
Apr-2013
May-2013
Jun-2013
.
.
.
Jan-2019
Feb-2019
Mar-2019       .

2 个答案:

答案 0 :(得分:1)

一个选项是将数据gather转换为“长”格式,并用“键”将unite的“年/月”列创建“期间”

library(tidyverse)
library(zoo)
gather(df1, key, val, -`Year/Month`) %>% 
     unite(Period, key, `Year/Month`, sep="-") %>% 
     mutate(Period = as.yearmon(Period, '%b-%Y')) %>%
     arrange(Period)
#    Period val
#1 Apr 2012 201
#2 May 2012 203
#3 Jun 2012 208
#4 Apr 2013 220
#5 May 2013 221
#6 Jun 2013 222

数据

df1 <- structure(list(`Year/Month` = 2012:2013, APR = c(201L, 220L), 
    MAY = c(203L, 221L), JUN = c(208L, 222L)), class = "data.frame", 
 row.names = c(NA, -2L))

答案 1 :(得分:0)

您可以这样做:

row.names(df) = df[,1]
with(data.frame(as.table(as.matrix(df[,-1]))),
         data.frame('Year-Month' = paste(Var1,Var2,sep='-'),Value=Freq))

或者您也可以这样做:

with(cbind(year=df[,1],stack(df[,-1])),
      data.frame(year=paste(year,ind,sep='-'),val=values)[order(year),])