Im trying to estimate the mean and standard deviation of an infinite stream of numbers. When I run my code I get an error message "cannot change value of locked binding"
I did some research and gather this error is related to my use of global variables but I am unable to figure it out. Any help would be much appreciated. Thanks in advance for your help
#define global variables
glength <<- 0
sum <<- 0
sumSq <<- 0
xBar <<- 0
SD <<- 0
#function with global variables
gF <- function() {
glength <<- 0
sum <<- 0
xBar <<- 0
sumSq <<- 0
SD <<- 0
}
#function prints the sample size, mean and standard deviation
rolngStats <- function() {
print(sprintf("n = %s; mean = %s; sd = %s", glength, xBar, SD))
}
rolngStats <- function(vector) {
for (element in vector) { #numbers in the vector
glength <<- glength + 1 #increment value in the vector by 1
sum <<- sum + element
xBar <<- sum/glength #calculate the mean
sumSq <<- sumSq + element^2
SD <<- sqrt((glength)* sumSq - sum^2)/(glength) #calculate standard deviation
if (glength %% 1000000 == 0) rolngStats()
}
return (c("n" = glength, "mean" = xBar, "sd" = SD))
}