lastvalues <- local(
{
   values <- c(); 
   function(x, len)
   {
      values <<- c(values, x); 
      lenv <- length(values); 
      if(lenv > len) values <<- values[(len-lenv):-1]
      values
   }
})


moving.average <- function(latestvalue, len=3)
{
   
   is.numeric.scalar <- function(x) is.numeric(x) && length(x)==1L
   if(!is.numeric.scalar(latestvalue) ||!is.numeric.scalar(len))
   {
      stop("all arguments must be numeric scalars")
   }

   
   mean(lastvalues(latestvalue, len))
}
moving.average(5)  
moving.average(1)  
moving.average(-3) 
moving.average(8)  
moving.average(7)