Cumulative standard deviation: Difference between revisions

m
m (→‎{{header|R}}: Improved syntax.)
Line 3,605:
==="Running" SD===
If we desire a solution that gives every "running" standard deviation for each input, rather than only giving one number as our final output, we can do the following. To make this differ from previous solutions, we will not have our code make any mention of missing values, and we will show off R's Reduce and sapply.
<lang rsplus>biasedSd <- function(data)#Once again, we have to make a standard deviation function from scratch.
biasedSd <- function(data) sqrt(mean((data - mean(data))^2))
{
cumSd <- function(data) sapply(Reduce(c, data, accumulate = TRUE), biasedSd)</lang>
sqrt(mean((data - mean(data))^2))
}
 
cumSd <- function(data)
{
sapply(Reduce(c, data, accumulate = TRUE), biasedSd)
}</lang>
{{out}}
<pre>> cumSd(c(2, 4, 4, 4, 5, 5, 7, 9))
[1] 0.0000000 1.0000000 0.9428090 0.8660254 0.9797959 1.0000000 1.3997084 2.0000000</pre>
 
===Stateful SD===
If we want a function that remembers and uses the previous inputs, letting us be very strict about the "one at a time" requirement, then we can lift biasedSd from the previous solution and make good use of the distinction between R's <- and <<- methods of assignment.
331

edits