-1

我的数据采用以下形式:

df <- data.frame(year=c(1992:2015), share=c(31.9,   36.8,   38.2,   39.9,   36.3,   36.5,   35.6,   35.2,   34.8,   33.2,   33.5,   34.6,   
                                            36.3,   36.2, 38.1, 37.2,   35.9,   33.2,   36.9,   36.0,   33.9,   33.7,   34.3,   35.1))

数据由年均值组成。假设变化是线性的,我想将数据转换为平均季度值。

我尝试使用library("tempdisagg"),但我无法让它工作。我还尝试了一些其他library("splines")的统计方法,但无济于事。也许是因为我错误地处理了日期和时间序列格式。

为了澄清,预期的输出看起来像这样:

y_q     share
1992q1  values
1992q2  values
1992q3  values
1992q4  values
1993q1  values
1993q2  values
1993q3  values
1993q4  values
1994q1  values
1994q2  values
1994q3  values
1994q4  values

任何帮助将非常感激。

4

2 回答 2

0

“近似”函数可以执行输出所需值的线性插值。

#create sequence of dates
quarter<-seq(as.Date("1992-01-01"), as.Date("2015-01-01"), by="quarter")
#create the linear interploated values
estshare<-approx(df$share, n=length(quarter))
newdf<-data.frame(quaters<-quarter, share<-estshare$y)

在这种情况下,我假设股价是从今年的第一天开始的。如果它是平均值,您可能希望更改日期序列的开始和结束日期,“季度”从年初到年中。

于 2016-08-17T13:50:35.297 回答
0

使用线性年度插值,您可以使用基本包尝试:

    annual <- data.frame(year=c(1992:2015), share=c(31.9, 36.8, 38.2, 39.9,  36.3, 36.5, 35.6, 35.2, 34.8, 33.2, 33.5, 34.6, 36.3, 36.2, 38.1, 37.2, 35.9, 33.2, 36.9, 36.0, 33.9, 33.7, 34.3, 35.1))
# Annual delta for interpolation
annual$delta<-c(NA, diff(annual$share,1))
# Quarterly table
ref<-data.frame(quarter=paste0("Q", 1:4), nb=1:4)
quart<-merge(annual, ref)
quart<-quart[order(quart$year, quart$quarter),]

# quarterly value calculation with evolution (loop)
quart$quarterly<-NA
quart$quarterly[1:4]<-quart$share[1:4]/4

for (i in (2:dim(annual)[1])) {     
quart$quarterly[quart$year==annual$year[i]] <- sum(quart$quarterly[quart$year==annual$year[i-1]])/4+ (quart$delta[quart$year==annual$year[i]] * quart$nb[quart$year==annual$year[i]])/10
 }
# /10 : /(1+2+3+4)
# Check :
summary(annual$share == aggregate(quarterly ~ year, data=quart, FUN=sum)[,2])
plot(quart$quarterly, typ="l")

它可能很难看,但我更喜欢使用基本函数来理解底层,所以我可以调整我的代码以适应其他情况。

于 2016-08-18T08:21:05.083 回答