重塑每日时间序列数据

reshaping daily time series data

我有从 1980 年开始到 2013 年结束的每日时间序列数据,格式如下 https://www.dropbox.com/s/i6qu6epxzdksvg7/a.xlsx?dl=0。到目前为止,我的代码是

   # trying to reshape my data
   require(reshape)
   data <- melt(data1, id.vars=c("year","month"))

然而,这并不是我想要的输出。我想将我的数据放在时间序列中的 4 列(年、月、日和数据)或 2 列(日期和数据)中(从 1980 年 1 月 1 日开始到 2013 年 12 月 31 日结束)

如果能提供有关如何完成此操作的指导,我将不胜感激。

谨致问候

我使用了你上传的数据,所以它为我读取如下:

dat<-read.csv('a.csv')
library(reshape)

newDF<-reshape(dat,direction='long',idvar=c('year','month'),varying=list(3:33),v.names='X')

newDF<-as.ts(newDF)

这是你想要的吗?

与 Jason 的结果相同,但使用 tidyr::gather 而不是 reshape

new.df <- gather(dat, key = year, value=month, na.rm = FALSE, convert = TRUE)
new.df$variable <- as.numeric(sub("X", "", new.df$var))
names(new.df)[3] <- "day"

new.df.ts <- as.ts(new.df)

head(new.df.ts)
     year month day value
[1,] 1980     1   1   2.3
[2,] 1980     2   1   1.0
[3,] 1980     3   1   0.0
[4,] 1980     4   1   1.8
[5,] 1980     5   1   3.8
[6,] 1980     6   1  10.4

扩展 Jason 的/Dominic 的解决方案,这为您提供了一个示例,说明如何按照您的要求将数据绘制为 xts 时间序列:

    library(xts)
    dat<-read.csv('~/Downloads/stack_a.csv')
    dat.m <-reshape(dat,direction='long',idvar=c('year','month'),varying=list(3:33),v.names='value')
    dat.m <- dat.m[order(dat.m[,1],dat.m[,2],dat.m[,3]),] # order by year, month, day(time) 
    dat.m$date <-paste0(dat.m$year,'-',dat.m$month,'-',dat.m$time) # concatenate these 3 columns
    dat.m <- na.omit(dat.m) # remove the NAs introduced in the original data 
    dat.xts <- as.xts(dat.m$value,order.by = as.Date(dat.m$date))
    names(dat.xts) <- 'value'
    plot(dat.xts)