Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

dplyr - Backward moving average with varying moving window size to keep the output series size same as the original time series in R

I have a long time series of a variable. I want to perform a backward moving average with window size of 20. If I keep this window size then the output series will be shortened by length 20 (I mean first 20 values will be NAs) but what I want is that the the output series should be of same length as original series with non NAs. For this, I want to vary the window size in the beginning so that I can get the desired output. For example, for the first 20 values in original time series, the moving window size can be 1, 2, 3, ...., 20, respectively. Then I want to keep the window size of 20 afterwards. How this can be done?

Here is the sample data and desired output with window size 3:

Days    Original_Values    Desired_Output
 1           2                  2
 2           4                  2
 3           1                  3
 4           3                  7/3
 5           5                  8/3
 6           6                  9/3
 7           4                  14/3
 8           9                  15/3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using the input shown reproducibly in the Note at the end, use rollapplyr specifying offsets -1, -2, -3 and use the argument partial=TRUE to let it use fewer than the specified offsets if only fewer are available. The first element cannot be calculated since there are no prior elements so for that specify that the first element be filled in using the fill argument.

library(zoo)

DF2 <- transform(DF, roll = 
  rollapplyr(Original, list(-(1:3)), mean, partial = TRUE, fill = Original[1]))

with(DF2, identical(Desired, roll))  # check that result matches Desired
## [1] TRUE

Note

Lines <- "
 Days        Original           Desired
 1           2                  2
 2           4                  2
 3           1                  3
 4           3                  7/3
 5           5                  8/3
 6           6                  9/3
 7           4                  14/3
 8           9                  15/3"
DF <- read.table(text = Lines, header = TRUE)
DF <- transform(DF, Desired = sapply(Desired, function(x) eval(parse(text = x))))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...