案例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。这是怎么回事?
发布于 2015-09-17 15:30:29
更新:
传递给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] 20https://stackoverflow.com/questions/32624602
复制相似问题