Averages/Simple moving average: Difference between revisions

Added R code
(→‎{{header|Java}}: found more repetition to kill)
(Added R code)
Line 387:
Next number = 2 , SMA = 3.8
Next number = 1 , SMA = 3 </pre>
 
=={{header|R}}==
This is easiest done with two functions: one to handle the state (i.e. the numbers already entered), and one to calculate the average.
<lang R>
#concat concatenates the new values to the existing vector of values.
concat <- local({values <- c(); function(x){values <<- c(values, x)}})
 
#moving.average accepts an arbitrary number of numeric inputs (scalars, vectors, matrices, arrays) and calculates the stateful moving average.
moving.average <- function(...)
{
#Flatten input variables
newvalues <- unlist(list(...), use.names=FALSE)
#Check that all inputs are numeric
if(!is.numeric(newvalues))
{
stop("all arguments must be numeric")
}
#Calculate mean of variables so far
mean(concat(newvalues))
}
moving.average(1,2,3) # 2
moving.average(4,5,6) # 3.5
moving.average(7:9) # 5
moving.average(matrix(1:12, ncol=3)) # 5.857143
</lang>
 
=={{header|Ruby}}==