Function - Scoping assignment and local bound and global variable in R

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I am new to R and trying to figure out behavior of local,bound and global variables. I am confused with the following problem. If I write the function in the following way, then what are the local, bound and global variables of function f?

f <- function(a ="") {
  return_a <- function() a
  set_a <- function(x)
      a <<- x
  list(return_a,set_a)
}

Answers

return_a is a function. set_a is a function. They are both functional objects (with associated environments, but using the word "variable" to describe them seems prone to confusion. If you call f, you get a list of twofunctions. When you create a list, there are not necessarily names to the list so p$set_a("Carl") throws an error because there is no p set_a .

> p <- f("Justin"); p$set_a("Carl")
Error: attempt to apply non-function

But p2 now returns a function and you need to call it:

>  p[[2]]
function(x)
      a <<- x
<environment: 0x3664f6a28>

> p[[2]]("Carl")

That did change the value of the symbol-a in the environment of p1:

> p[[1]]()
[1] "Carl"

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/28555376/scoping-assignment-and-local-bound-and-global-variable-in-r

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils