File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
1
+ # modifying parent scope variable
2
+ new_counter <- function () {
3
+ i <- 0 # this is the variable being modified
4
+ function () {
5
+ i <<- i + 1 # modifies parent scope variable
6
+ i # prints parent scope variable
7
+ }
8
+ }
9
+ counter_one <- new_counter()
10
+ counter_two <- new_counter()
11
+ counter_one() # [1] 1
12
+ counter_one() # [1] 2
13
+ counter_two() # [1] 1
14
+
15
+ # parent scope variable overshadowed by the current scope variable
16
+ new_counter <- function () {
17
+ i <- 0 # this variable will be overshadowed
18
+ function () {
19
+ i <- 42 # overshadows the parent scope variable
20
+ i <<- i + 1 # modifies current scope variable
21
+ i # prints current scope variable
22
+ }
23
+ }
24
+ counter_one <- new_counter()
25
+ counter_two <- new_counter()
26
+ counter_one() # [1] 43
27
+ counter_one() # [1] 43
28
+ counter_two() # [1] 43
29
+
30
+ # modified example from 02.10 Scoping Rules: R Scoping Rules
31
+ y <- 10
32
+ f <- function (x ) {
33
+ y <- 2 # overshadows the global scope variable
34
+ y ^ 2 + g(x ) # uses current scope variable (value 2)
35
+ }
36
+ g <- function (x ) {
37
+ y <<- y + 42 # modifies gloval scope variable (42 added to y, which is 10 at the beginning)
38
+ x * y # uses global scope variable (value 42), because g is defined in global environment
39
+ }
40
+ f(3 ) # 2^2 + 3*52 = 160
41
+ y # 42 (changed by call to g)
42
+ f(3 ) # 2^2 + 3*94 = 286
43
+ y # 94 (changed by call to g)
44
+
45
+
46
+ # vim: set ts=2 sw=2 noet:
47
+
48
+
You can’t perform that action at this time.
0 commit comments