0

CASE 1:

x <- 10
f <- function(x){
  x <- 20
  x}
f(x)
# [1] 20
x
# [1] 10

I am satisfied with the output.

CASE 2:

x <- 10
f <- function(x){
  x <<- 20
  x}
f(x)
# [1] 20
x
# [1] 20

I expect the output of f(x) to be 10 not 20 because function f should return local value of x i.e. 10. I am totally confused.

CASE 3:

x <- 10
f <- function(x){
  x <<- 20
  x}
f(10)
# [1] 10
x
# [1] 20

In this case f(10) returns 10 not 20 as in CASE 2. What is going on?

cryptomanic
  • 5,986
  • 3
  • 18
  • 30
  • 2
    In the second case, you assigned `20` to `x` in the **global** environment. –  Sep 17 '15 at 07:22
  • 4
    Isn't this the same problem explained [here](http://stackoverflow.com/questions/32623856/difference-between-and) – akrun Sep 17 '15 at 07:22
  • for your study https://stat.ethz.ch/R-manual/R-devel/library/base/html/assignOps.html – Dhawal Kapil Sep 17 '15 at 07:24
  • 1
    @ Pascal agreed that global value of x is 20. But the function f should return the local value of x which is 10 – cryptomanic Sep 17 '15 at 07:25
  • No, it is `20`. `x <<- 20` –  Sep 17 '15 at 07:26
  • That is why it is not recommended to use `<<-`. –  Sep 17 '15 at 07:28
  • @Pascal There can be good reasons to use `<<-` , e.g., in parallel computing; but I think that this goes too far here. Opinions differ on whether it is generally recommended not to use `<<- `. – RHertel Sep 17 '15 at 07:32
  • @RHertel Even in parallel computing, I don't use `<<-`. But yes, it is as matter of opinion. –  Sep 17 '15 at 07:36
  • It appears that @DeepakYadav actually hit onto a very interesting feature of the R language. – Tim Biegeleisen Sep 17 '15 at 08:05

1 Answers1

0

Update:

It appears that the parameter passed to an R function is a reference to the value which was passed to it. In other words, if the variable outside an R function which was passed in gets changed, then the local variable inside the function will also change. Here are your cases 2 and 3 with comments:

Case 2:

x <- 10
f <- function(x) {
    x <<- 20        # global x is assigned to 20
    x               # therefore local x, which is a reference to
}                   # the x passed in, also changes
f(x)
# [1] 20
x
# [1] 20

Case 3:

x <- 10
f <- function(x) {
    x <<- 20        # global x is assigned to 20
    x               # but local x, which references a temporary variable having
}                   # the value of 10, is NOT changed by the global
f(10)               # assignment operator
# [1] 10            # therefore the value 10 is returned
x
# [1] 20
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360