Tutorial by Examples

Variables declared inside a function only exist (unless passed) inside that function. x <- 1 foo <- function(x) { y <- 3 z <- x + y return(z) } y Error: object 'y' not found Variables passed into a function and then reassigned are overwritten, but only insi...
Functions called within a function (ie subfunctions) must be defined within that function to access any variables defined in the local environment without being passed. This fails: bar <- function() { z <- x + y return(z) } foo <- function() { y <- 3 z <-...
Variables can be assigned globally from any environment using <<-. bar() can now access y. bar <- function() { z <- x + y return(z) } foo <- function() { y <<- 3 z <- bar() return(z) } foo() 4 Global assignment is highly discourag...
Environments in R can be explicitly call and named. Variables can be explicitly assigned and call to or from those environments. A commonly created environment is one which encloses package:base or a subenvironment within package:base. e1 <- new.env(parent = baseenv()) e2 <- new.env(parent ...
The on.exit() function is handy for variable clean up if global variables must be assigned. Some parameters, especially those for graphics, can only be set globally. This small function is common when creating more specialized plots. new_plot <- function(...) { old_pars <- par(m...
Functions and objects in different packages may have the same name. The package loaded later will 'mask' the earlier package and a warning message will be printed. When calling the function by name, the function from the most recently loaded package will be run. The earlier function can be accessed ...

Page 1 of 1