gpt4 book ai didi

r - 为什么在 system.time() 中评估表达式会使变量在全局环境中可用?

转载 作者:行者123 更新时间:2023-12-04 00:39:59 25 4
gpt4 key购买 nike

有人能解释一下在 system.time 中计算表达式时会发生什么吗? ?特别是,为什么在 expr 中声明了任何变量?论证在全局环境中可见?

这是 system.time 的内脏的精简版除了计算传递给函数的表达式外,什么都不做:

st <- function(expr){
expr
}

st(aa <- 1)
aa
[1] 1

显然,这样做的效果是它创建了变量 aa在全局环境中。这让我感到困惑,因为我认为在函数内部分配变量会使它在范围内成​​为局部变量。

这里会发生什么?

最佳答案

这是因为提供的参数 在调用函数的求值框架中求值(如 R 语言定义文档的 Section 4.3.3 中所述)。

用户包裹在 system.time() 中的表达式是一个提供的参数,它在位置上与 expr 匹配.然后,当 expr的评价被强加在system.time的正文中,它在调用函数的求值框架中求值。如 system.time()是从 .GlobalEnv 调用的,这是 expr 的任何分配的位置将发生。

编辑:

这是一个示例,显示 expr如果是 ,则在全局环境中进行评估提供 (但不是 默认 )参数。

st2 <- function(expr = newVar <- 33){
expr
}

# Using the default argument -- eval and assignment
# within evaluation frame of the function.
st2()
newVar
Error: object 'newVar' not found

# Using a supplied argument -- eval and assignment
# within the calling function's evaluation frame (here .GlobalEnv)
st2(newVar <- 44)
newVar
# [1] 44

关于r - 为什么在 system.time() 中评估表达式会使变量在全局环境中可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7972655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com