[英]Passing arguments to a function in R
CASE 1: 情况1:
x <- 10
f <- function(x){
x <- 20
x}
f(x)
# [1] 20
x
# [1] 10
I am satisfied with the output. 我对输出感到满意。
CASE 2: 情况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. 我希望f(x)的输出是10而不是20,因为函数f应该返回x的局部值,即10。我完全感到困惑。
CASE 3: 情况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? 在这种情况下,
f(10)
返回10而不是案例2中的20。这是怎么回事?
Update: 更新:
It appears that the parameter passed to an R function is a reference to the value which was passed to it. 似乎传递给R函数的参数是对传递给它的值的引用。 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.
换句话说,如果传入的R函数外部的变量发生了变化,则函数内部的局部变量也将发生变化。 Here are your cases 2 and 3 with comments:
这是您的案例2和3,并有注释:
Case 2: 情况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: 情况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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.