亲爱的
我正在尝试使用R将季度数据分解为月度数据。我不关心日期,因为我可以毫无问题地生成对应于值的月份向量。问题出在值的向量和缺失数据的推算上。如下例所示:
Quarter Value
2010-Q1 10
2010-Q2 15
2010-Q3 18
2010-Q4 12新数据集应如下所示
Month Value
2010-3 10
2010-4 11.67
2010-5 13.34
2010-6 15
2010-7 16
2010-8 17
2010-9 18
2010-10 16
2010-11 14
2010-12 12现在,使用以下公式填充每个季度内的月份
The first month of the quarter[i] = The previous quarter value [i-1] + ((The difference between the quarter [i] and [i-1])/3)
The second month of the quarter[i] = The previous quarter value [i-1] + 2*((The difference between the quarter [i] and [i-1])/3)例如:
2020-Q1 = 10
2020-Q2 = 15
差异/3= 5/3
2020-4月= 10 +差异
2020-5月= 10 +2*差异
2020-6月= 15 (季度末保持不变)或可计算为10 +3*差异
我想知道如何生成一个新的变量来分解上面提到的值。
谢谢
发布于 2021-02-14 20:48:13
1)将输入转换为具有yearqtr索引(直接表示年和季度,不含月或日)的动物园系列z,然后使用NAs填充并应用na.approx来线性填充给定的Value。假设序列有规律的间隔,我们只需使用每年12个月的频率将第一个索引值转换为yearmon (它直接表示不含日的年和月)。最后,将其保留为Value,或者使用最后一行将其转换回数据帧DF2。另一种可能是使用as.ts(Value)将其转换为ts系列。
请注意,yearmon类如下所示,但在内部将年和月表示为year加上分数等于0(表示Jan )、1/12 (表示Feb )、11/12 (表示Dec ),因此as.integer(time(Value))将提供年份,cycle(time(Value))将提供月份数字(Jan = 1,...,Dec = 12)。
library(zoo)
z <- read.zoo(DF, FUN = function(x) as.yearqtr(x, "%Y-Q%q"))
Value <- zooreg(na.approx(c(t(cbind(z, NA, NA)))),
start = as.yearmon(start(z)), freq = 12)
DF2 <- fortify.zoo(Value) # optional给予:
> DF2
Index Value
1 Jan 2010 10.00000
2 Feb 2010 11.66667
3 Mar 2010 13.33333
4 Apr 2010 15.00000
5 May 2010 16.00000
6 Jun 2010 17.00000
7 Jul 2010 18.00000
8 Aug 2010 16.00000
9 Sep 2010 14.00000
10 Oct 2010 12.00000从图形上看,它是这样的:
plot(Value, type = "o")(打印后继续)

2)以(1)中的z开始的第二种方法是首先创建输出yearmon时序tt,将z的时间索引转换为yearmon z.ym,然后将它们合并生成NA,最后应用na.approx填充它们。
tt <- seq(as.yearmon(start(z)), as.yearmon(end(z)), 1/12)
z.ym <- aggregate(z, as.yearmon, c)
Value <- na.approx(merge(z.ym, zoo(, tt)))备注
可重现形式的输入:
Lines <- "Quarter Value
2010-Q1 10
2010-Q2 15
2010-Q3 18
2010-Q4 12"
DF <- read.table(text = Lines, header = TRUE)https://stackoverflow.com/questions/66193187
复制相似问题