Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 833d801

Browse files
committed
Examples explaining lexical scoping and <<- operator used in R
1 parent 7f657dd commit 833d801

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

scopes.R

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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+

0 commit comments

Comments
 (0)