>From Pat Welch I learned that the filter() function can be used to
calculate moving averages. Although it is a little convoluted for an
armchair statistician like me. He also offered a moving average function
that allows the window to expand over time.
--Jim Robinson-Cox offered a function, (three versions actually) to calculated a statistic on a moving window.
moving.fn <- function(x, window.size, fun = mean) { result <- 1:(length(x) - window.size+1) for(i in result) result[i] <- fun(x[i:(i + window.size-1)]) result }
Or if you are willing to use more memory to avoid a loop (which I thought was the reason for avoiding loops).
move.fn <- function(x,window.size,fun=mean){ lx <- length(x) xmat <- matrix(x[1:window.size + rep(0:(lx-window.size), rep(window.size,lx-window.size+1))], nrow=window.size) apply(xmat,2,fun) }
Or a third version using lapply:
> move3.fn <- function(x,window.size,fun=mean){ + len <- length(x)-window.size+1 + xsplit <- vector("list",len) + for(i in 1:len) xsplit[[i]] <- x[1:window.size + i-1] + unlist(lapply(xsplit,fun)) + }
> x [1] 47 25 38 46 45 44 31 27 50 35 > move.fn(x,3) [1] 36.66667 36.33333 43.00000 45.00000 40.00000 34.00000 36.00000 37.33333 > move.fn(x,3,max) - move.fn(x,3,min) [1] 22 21 8 2 14 17 23 23
Then to make a Moving Range control chart use the function to find the moving range and plot the line. Control limits and such would have to be developed and and added to make the whole thing complete. This is a nicely simple solution.
> x <- c( 47, 25, 38, 46, 45, 44, 31, 27, 50, 35)
> moving.fn(x,3) ## mean is default [1] 39.00 38.50 43.25 41.50 36.75 38.00 35.75
Do it with max - min to get range: > mv.range <- moving.fn(x,3,max)-moving.fn(x,3,min) > mv.range [1] 22 21 8 15 18 23 23
so then you just plot as in:
plot(1:length(mv.range), mv.range, type="b", xlab="Run", ylab="Moving Range")
--Daniel Rie suppplied the pot of gold in his response pointing to qtoolbox, (worth repeating that you can find it at http://www.dms.csiro.au/world/S-PLUS/qtoolbox/). I haven't tried out the actually code yet but the manual tells me it has the moving average and moving range charts for individual values that are just what I wanted to find. There are a number of other quality control goodies that look interesting also.
-- Thanks to all that took time to think about my problem. Marty Goss-- =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Marty Goss Hewlett Packard goss@spk.hp.com 24001 E. Mission Ave Telnet 921-3734 Liberty Lake, WA 99019-9599 =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ----------------------------------------------------------------------- This message was distributed by s-news@wubios.wustl.edu. To unsubscribe send e-mail to s-news-request@wubios.wustl.edu with the BODY of the message: unsubscribe s-news