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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With