Mohit Sharma: LinkedIn, Twitter
GitHub Site, Repository
Super assignment operator <<-
can be used for assignment in parent environment. Which of the following is TRUE for the following code?
x <- 0
f <- function(){
x <<- x + 1
x
}
#1st execution
A = f()
#2nd execution
B = f()
#3rd execution
C = f()
<<-
is known as super assignment operator. In contrast to the regular assignment operator <-
which does the assignment in current environment, <<-
does the assignment in parent environment. If in case it doesn’t find the variable, it will create the variable in global environment. See for example below:
I have defined a function f
with a variable y
in it to which I have assigned 1. If I try to access y
outside function, I get the error, as y
doesn’t exist in global environment. It only exists in f
’s environment.
f <- function(){
y <- 1
}
#function call
f()
y
## Error in eval(expr, envir, enclos): object 'y' not found
But if I rewrite the above code using <<-
, I don’t get any error. y
is now defined in global environment.
f <- function(){
y <<- 1
}
#function call
f()
y
## [1] 1
So for the above question, option \(2.\) \(C>B>A\) is correct.
x <- 0
f <- function(){
x <<- x + 1
x
}
#1st execution
A = f()
#2nd execution
B = f()
#3rd execution
C = f()
As C=3
, B=2
, A=1
. At the first execution, f
returns 1
and also updates x
in global environment to 1
. Similarly for the subsequent executions, x
gets updated globally with an increment 1.
A
## [1] 1
B
## [1] 2
C
## [1] 3
In contrast, if I use <-
, I would get A=B=C=1
.
x <- 0
f <- function(){
x <- x + 1
x
}
#1st execution
A = f()
#2nd execution
B = f()
#3rd execution
C = f()
A
## [1] 1
B
## [1] 1
C
## [1] 1
References: Advanced R by Hadley Wickham
Thanks for reading. If you like the question, how about some love and coffee: Buy me a coffee