R Error: cannot change value of locked binding

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-12 23:46:51

问题


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))

}

来源:https://stackoverflow.com/questions/42869577/r-error-cannot-change-value-of-locked-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!