简体   繁体   中英

Passing arguments to a function in R

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 ie 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM