Read the time series table using read.zoo

I looked everywhere, but I can’t find where this question was asked before.

What a clean way to get this data in the right zoo series? This version is copy / paste to make this post easier, but it will always be displayed in the following tabular form (from a text file). The read.zoo () operator reads Year as an index, but quarters (Qtr1, Qtr2, etc.) are read as column names. I was trying to understand that a non-garbage way to read columns as a “quarter” of the index, but it is sloppy (too messy to publish). I assume that this problem has already been solved, but I can not find it.

> texinp <- " + Year Qtr1 Qtr2 Qtr3 Qtr4 + 1992 566 443 329 341 + 1993 344 212 133 112 + 1994 252 252 199 207" > z <- read.zoo(textConnection(texinp), header=TRUE) > z 

In the as.yearqtr () documentation, the goal will look like this:

 1992 Q1 1992 Q2 1992 Q3 1992 Q4 1993 Q1 1993 Q2 1993 Q3 1993 Q4 566 443 329 341 344 212 133 112 1994 Q1 1994 Q2 1994 Q3 1994 Q4 252 252 199 207 
+4
source share
2 answers

Read the data with read.zoo and then convert it to a zooreg object with index yearqtr :

 texinp <- "Year Qtr1 Qtr2 Qtr3 Qtr4 1992 566 443 329 341 1993 344 212 133 112 1994 252 252 199 207" library(zoo) z <- read.zoo(text = texinp, header=TRUE) zz <- zooreg(c(t(z)), start = yearqtr(start(z)), freq = 4) 

The result is as follows:

 > zz 1992 Q1 1992 Q2 1992 Q3 1992 Q4 1993 Q1 1993 Q2 1993 Q3 1993 Q4 1994 Q1 1994 Q2 1994 Q3 1994 Q4 566 443 329 341 344 212 133 112 252 252 199 207 
+3
source

read.zoo assumes that your data has no more than one column with a time index, so you will have to process this yourself. Read it first when using read.table

 zt <- read.table( textConnection( texinp ), header = TRUE) 

then convert it to a "long table" using the melt function from the reshape package:

 require(reshape) zt.m <- melt( zt, id = 'Year', variable_name = 'Qtr') > zt.m Year Qtr value 1 1992 Qtr1 566 2 1993 Qtr1 344 3 1994 Qtr1 252 4 1992 Qtr2 443 5 1993 Qtr2 212 6 1994 Qtr2 252 7 1992 Qtr3 329 8 1993 Qtr3 133 9 1994 Qtr3 199 10 1992 Qtr4 341 11 1993 Qtr4 112 12 1994 Qtr4 207 

and finally create the desired zoo object:

 z <- with( zt.m, zoo( value, as.yearqtr(paste(Year, Qtr), format = '%Y Qtr%q'))) > z 1992 Q1 1992 Q2 1992 Q3 1992 Q4 1993 Q1 1993 Q2 1993 Q3 1993 Q4 1994 Q1 1994 Q2 566 443 329 341 344 212 133 112 252 252 1994 Q3 1994 Q4 199 207 
+3
source

Source: https://habr.com/ru/post/1335786/


All Articles