首页 文章

重塑每日时间序列数据

提问于
浏览
1

我有从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日结束)

我将非常感谢有关如何完成这项工作的一些指导 .

亲切的问候

3 回答

  • 2

    扩展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)
    
  • 1

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

    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)
    

    那是你想要的吗?

  • 2

    与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
    

相关问题