Master R

By Guangming Lang Comment

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 one of the exercises.

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.

The best way to become a master in R is to learn from the masters. You can buy a copy of Hadley’s book Advanced R from Amazon.

If you enjoyed this post, get updates. It's FREE