简体   繁体   English

重塑每日时间序列数据

[英]reshaping daily time series data

I have daily time series data starting from 1980 and ends at 2013 and it is the following format https://www.dropbox.com/s/i6qu6epxzdksvg7/a.xlsx?dl=0 . 我有从1980年开始到2013年结束的每日时间序列数据,它是以下格式https://www.dropbox.com/s/i6qu6epxzdksvg7/a.xlsx?dl=0 My codes thus far are 到目前为止,我的代码是

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

However, this did not me my desired output. 但是,这不是我想要的输出。 I would like to have my data in a 4 columns ( year, month, day and data ) or 2 columns with ( date and data) in a time series ( starting from 1st Jan 1980 and ends 31st Dec 2013) 我想将我的数据按时间序列(从1980年1月1日开始,到2013年12月31日)分为4列(年,月,日和数据)或2列(日期和数据)。

I would be grateful for some guidance on how to get this done. 感谢您提供有关如何完成此操作的指导。

With kind regards 亲切的问候

I used the data you uploaded so it read for me like follows: 我使用了您上传的数据,因此对我来说如下所示:

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)

Is that what you wanted? 那是你想要的吗?

Same results as Jason's, but using tidyr::gather instead of reshape 相同的结果,贾森的,但使用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

Extending Jason's / Dominic's solution this gives you an example of how to plot your data as a xts time series as you asked for: 扩展了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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM