by Guangming Lang
~1 min read

Categories

  • r

The regular assignment arrow <- always creates a variable in the current environment. The deep assignment arrow <<- never creates a variable in the current environment, but instead modifies an existing variable in the parent environments. You can also do deep binding with assign(): name <<- value is equivalent to assign("name", value, inherits = TRUE). If <<- doesn’t find an existing variable, it will create one in the global environment. This is usually undesirable because global variables introduce non-obvious dependencies between functions.

In the Environments chapter of Hadley’s book Advanced R, he gave the following function in exercise.

rebind = function(name, value, env = parent.frame()) {
        if (identical(env, emptyenv())) {
                stop("Can't find ", name, call. = FALSE)
        } else if (exists(name, envir = env, inherits = FALSE)) {
                assign(name, value, envir = env)
        } else {
                rebind(name, value, parent.env(env))
        }
}

It behaves like <<- except when failing to find an existing variable, it runs into an error and stops.