[英]Read a time series table using read.zoo
I've looked all over the place, but I can't find where this question has been asked before. 我到处都看了,但我找不到以前问这个问题的地方。
What is a clean way to get this data into a proper zoo series? 将这些数据导入适当的动物园系列的简洁方法是什么? This version is a copy/paste to make this post easier, but it will always come in the following table form (from a text file). 此版本是复制/粘贴,以使此帖子更容易,但它将始终以下表格式(来自文本文件)。 My read.zoo() statement reads the Year as the index but the quarters (Qtr1, Qtr2, etc) are read as column names. 我的read.zoo()语句将Year作为索引读取,但是季度(Qtr1,Qtr2等)被读作列名。 I've been trying to figure out a non-garbage way to read the columns as the "quarter" part of the index, but it's sloppy (too sloppy to post). 我一直试图找出一种非垃圾方式来读取列作为索引的“四分之一”部分,但它很草率(太松散了,不能发布)。 I'm guessing this problem has already been solved, but I can't 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
From the as.yearqtr() documentation, the target would look like: 从as.yearqtr()文档中,目标看起来像:
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
read.zoo
assumes your data has at most one time-index column, so you have to process this yourself. read.zoo
假设您的数据最多只有一个时间索引列,因此您必须自己处理。 First read it in using read.table
首先使用read.table
读取它
zt <- read.table( textConnection( texinp ), header = TRUE)
then convert it to a "long table" using the melt
function from the reshape
package: 然后使用reshape
包中的melt
函数将其转换为“long table”:
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 your desired zoo
object: 最后创建所需的zoo
对象:
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
Read in the data using read.zoo
and then convert it to a zooreg
object with yearqtr
time index: 使用read.zoo
读入数据,然后使用yearqtr
时间索引将其转换为zooreg
对象:
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 looks like this: 结果如下:
> 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.