[英]Passing arguments to a function in R
情况1:
x <- 10
f <- function(x){
x <- 20
x}
f(x)
# [1] 20
x
# [1] 10
我对输出感到满意。
情况2:
x <- 10
f <- function(x){
x <<- 20
x}
f(x)
# [1] 20
x
# [1] 20
我希望f(x)的输出是10而不是20,因为函数f应该返回x的局部值,即10。我完全感到困惑。
情况3:
x <- 10
f <- function(x){
x <<- 20
x}
f(10)
# [1] 10
x
# [1] 20
在这种情况下, f(10)
返回10而不是案例2中的20。这是怎么回事?
更新:
似乎传递给R函数的参数是对传递给它的值的引用。 换句话说,如果传入的R函数外部的变量发生了变化,则函数内部的局部变量也将发生变化。 这是您的案例2和3,并有注释:
情况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
情况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.