案例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而不是20,如案例2中所示。发生了什么?
答案 0 :(得分:0)
<强>更新强>
传递给R函数的参数似乎是对传递给它的值的引用。换句话说,如果传入的R函数外部的变量发生了变化,那么函数内的 local 变量也会发生变化。以下是您的案例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