Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding R's scoping demo

Tags:

r

scoping

I try to understand the scoping demo in R you can access through demo(scoping).

I do not understand where the total variable is saved. First off I thought according to help("<<-")

The operators <<- and ->> are normally only used in functions, and cause a search to made through parent environments for an existing definition of the variable being assigned. If such a variable is found (and its binding is not locked) then its value is redefined, otherwise assignment takes place in the global environment.

it is in the global environment. But since I cannot find it there (ls(environment)) I guess open.account <- function(total) creates one total variable for all instances created by an assignment of open.account(). But if I create an instance ross <- open.account(100) I cannot find the variable.

ross
...
<environment: 0x0000000011fbe998>

with ls(environment(environment: 0x0000000011fbe998)). The result of getAnywhere(total) is no object named ‘total’ was found. So where do live the different versions of total?

like image 927
ruedi Avatar asked Dec 02 '25 17:12

ruedi


1 Answers

The functions in the ross list are closures., i.e., functions with data. (Technically, most functions in R are closures. But usually you don't care about that.)

All these closures were defined within a call to open.account, so they are associated with the same environment "which provides the enclosure of the evaluation frame when the closure is used" (see help("closure")).

total is defined in this environment.

ross <- open.account(100)

environment(ross$deposit)
#<environment: 0x000000000ae10db8>
environment(ross$withdraw)
#<environment: 0x000000000ae10db8>
environment(ross$balance)
#<environment: 0x000000000ae10db8>

environment(ross$deposit)$total
#[1] 100
like image 155
Roland Avatar answered Dec 04 '25 06:12

Roland