R中函数内部变量的范围

问题描述 投票:0回答:1

我有以下代码:

a <- 10
b <- 3
c <- 4
addme <- function(a,b) {
  delta = a + b + c
  return(delta)
}
addme(a,b)

它返回17,但我不明白为什么如果在函数内部未定义变量c,难道它不应该只是0并返回13吗?为什么将值带到函数之外?

我已经阅读了一些有关<-的范围,环境和全局赋值的文字,但找不到与函数内部变量相关的内容。

任何帮助将不胜感激。

r
1个回答
0
投票

这是一个很好的代表,可以帮助您演示环境在R中应用于功能的作用:

var <- 10

f <- function()
{
  cat("Before function's var declared, var is", var, "\n")
  var <- 5
  cat("After function's var declared, var is", var, "\n")
  this_functions_environment <- environment()
  calling_environment <- parent.env(this_functions_environment)
  cat("In the function's environment, var is", this_functions_environment$var)
  cat("\nIn the calling environment, var is", calling_environment$var)
}

f()
#> Before function's var declared, var is 10 
#> After function's var declared, var is 5 
#> In the function's environment, var is 5
#> In the calling environment, var is 10

reprex package(v0.3.0)在2020-04-28创建

© www.soinside.com 2019 - 2024. All rights reserved.