R Error - cannot change value of locked binding for 'df'

前端 未结 4 1253
日久生厌
日久生厌 2021-02-14 06:00

I\'m trying to filter some data, with functions in R relatives to data frames. But in the second function, it gives me the following error: cannot change the value of locked bin

4条回答
  •  情话喂你
    2021-02-14 06:32

    Sometimes, one does want to violate the spirit of functional languages.

    I am not sure why, in R, a locked function prevents you from creating a variable at the same level, but the problem the OP has is because the function df() is locked in an environment above that of the current environment (which <<- finds).

    Here is some code (probably not the best) to find the environment in which df is (already) bound (i.e., already exists), and then check to see if it is, in fact, locked in that environment.

    > x <- environment(); while(TRUE) { print(exists("df", x)); x <- parent.env(x) }
    [1] TRUE
    [1] TRUE
    [1] TRUE
    [1] FALSE
    [1] FALSE
    [1] FALSE
    [1] FALSE
    [1] FALSE
    [1] FALSE
    [1] FALSE
    [1] FALSE
    Error in parent.env(x) : the empty environment has no parent
    > bindingIsLocked("df", parent.env(parent.env(environment())))
    [1] TRUE
    > 
    

    In this case, creating a variable df in the "global" context should solve the problem. i.e.,

    df <- NULL
    
    filter.data = function(x, dir = ".") {
        load.data(x, dir)
        df <<- dados_reais[,c(1,2,3,4,9,10,12)]
    }
    

    Alternatively, changing the name of the variable (from df, say, to myveryowndf) should also fix the problem.

提交回复
热议问题