Non-functional elements in R

This list is from John’s lecture:

  1. Operators and functions with side effects: (<<-, assign(), options(foo=))
  2. Nonstandard R objects: environments, connections.
  3. Random number generation
  4. Special mechanisms-“closures”

According to the R language definition, environments are mutable objects, so changes are visible outside of the function. R closures can have side effects due to the fact that when an R function returns a list of closures, these closures share the same environment. Since the environment is mutable, using <<- in the any of the closures will affect the other closures as well.

Example (inspired by a more involved example in John’s Software for Data Analysis):

> Counter <- function(start) {
+ t <- start
+ list(
+ inc = function() {t <<- t+1; t},
+ dec = function() {t <<- t-1; t} )
+ }
> counter <- Counter(5)
> counter[["dec"]]()
[1] 4
> counter[["dec"]]()
[1] 3
> counter[["inc"]]()
[1] 4

The Counter function returns a list of two functions “inc” and “dec”. Both functions are associated with the same environment. Thus successive calls to “inc” and “dec” operate on the same t variable. This use of closures has become largely out of date with the addition of S4 objects to the language.

Category: Uncategorized | Tags: Comment »

Leave a Reply

Back to top