我正在使用不平衡,不规则间隔的横截面时间序列。我的目标是获得“数量”向量的滞后移动平均向量,按“主题”分段。
换句话说,对于Subject_1,已经观察到以下Quanatities: [1,2,3,4,5]。我首先需要将其滞后1,产生[NA,1,2,3,4]。
然后我需要采用3阶移动平均线,产生[NA,NA,NA,(3 + 2 + 1)/ 3,(4 + 3 + 2)/ 3]
需要对所有受试者进行上述操作。
# Construct example balanced panel DF
panel <- data.frame(
as.factor(sort(rep(1:6,5))),
rep(1:5,6),
rnorm(30)
)
colnames(panel)<- c("Subject","Day","Quantity")
#Make panel DF unbalanced
panelUNB <- subset(panel,as.numeric(Subject)!= Day)
panelUNB <- panelUNB[-c(15,16),]
如果面板是平衡的,我将首先使用包plm
和函数lag
滞后“数量”变量。
然后,我将使用包rollmean
中的函数zoo
来获取滞后“Quanatity”的移动平均值:
panel$QuantityMA <- ave(panel$Quantity, panel$Subject, FUN = function(x) rollmean(
x,3,align="right",fill=NA,na.rm=TRUE))
当应用于平衡的“面板”DF时,这将产生正确的结果。
问题在于plm
和lag
依赖于均匀间隔的系列来生成索引变量,而rollapply要求所有主体的观察数(windowsize)相等。
StackExchange上有解决方案,data.table提示我的问题的解决方案:Producing a rolling average of an unbalanced panel data set
也许可以修改此解决方案以产生固定长度的移动平均线而不是“滚动累积平均值”。
答案 0 :(得分:2)
这会给你带来预期的效果吗?
library(reshape2)
library(zoo)
# create time series where each subject have an observation at each time step
d1 <- data.frame(subject = rep(letters[1:4], each = 5),
day = rep(1:5, 4),
quantity = sample(x = 1:4, size = 20, replace = TRUE))
d1
# select some random observations
d2 <- d1[sample(x = seq_len(nrow(d1)), size = 15), ]
d2
# reshape to wide format with dcast
# -> 'automatic' extension from irregular to regular series for each subject,
# _given_ that all time steps are represented.
# Alternative method below more explicit
# fill for structural missings defaults to NA
d3 <- dcast(d2, day ~ subject, value.var = "quantity")
d3
# convert to zoo time series
z1 <- zoo(x = d3[ , -1], order.by = d3$day)
################################
# alternative method to extend time series
# time steps to include are given explicitly
# create a zero-dimensional zoo series
z0 <- zoo(, min(d1$day):max(d1$day))
# extend z1 to contain the same time indices as z0
z1 <- merge(z1, z0)
################################
# lag, defaults to one unit
z2 <- lag(x = z1)
z2
# calculate rolling mean with window width 3
rollmeanr(x = z2, k = 3)
# Handling of NAs:
# from ?rollmean:
# "The default method of rollmean does not handle inputs that contain NAs.
# In such cases, use rollapply instead.":
rollapplyr(data = z2, width = 3, FUN = mean, na.rm = TRUE)
答案 1 :(得分:1)
所以,回答我自己的问题,一种方法是通过split-lapply(rollingaverage)-unlist:
Temp <-with(panelUNB, split(Quantity, Subject))
Temp <- lapply(Temp, FUN=function (x) rollapplyr(
x,2,align="right",fill=NA,na.rm=TRUE, FUN=mean))
QuantityMA <-unlist(Temp)
然后必须将“QuantityMA”向量添加回主“panelUNB”帧。似乎工作。滞后可以在ddply的不平衡面板上完成。
如果有人有另一个,也许更优雅的解决方案,欢迎您分享。