将参数传递给R中的函数

将参数传递给R中的函数,r,function,R,Function,案例1: x更新: x <- 10 f <- function(x){ x <<- 20 x} f(10) # [1] 10 x # [1] 20 x <- 10 f <- function(x) { x <<- 20 # global x is assigned to 20 x # therefore local x, which is a reference to }

案例1:


x更新:

x <- 10
f <- function(x){
  x <<- 20
  x}
f(10)
# [1] 10
x
# [1] 20
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
似乎传递给R函数的参数是对传递给它的值的引用。换句话说,如果传入的R函数外部的变量发生变化,则函数内部的局部变量也会发生变化。以下是您的案例2和案例3及其评论:

案例2:

x <- 10
f <- function(x){
  x <<- 20
  x}
f(10)
# [1] 10
x
# [1] 20
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

x在第二种情况下,您在全球环境中将
20
分配给
x
。这不是为您的研究解释的同一问题吗@Pascal同意x的全局值为20。但是函数f应该返回x的局部值,即10No,它是
20
<代码>x,但是案例3呢。在这种情况下,为什么没有按照您关于案例2的回答将局部变量赋值为20。@DeepakYadav,因为使用
f(10)
10
将局部变量赋值给
x
@Pascal,谢谢您的评论,但这实际上并不能解释它。@TimBiegeleisen当然可以。如果您有其他解释,请分享。@Tim如果参数是通过引用传递的,那么在案例1中全局变量的值应该是20,但事实并非如此。
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