gpt4 book ai didi

r - 如何在 R 的闭包中查询符号的值?

转载 作者:行者123 更新时间:2023-12-04 11:06:55 25 4
gpt4 key购买 nike

如何在下面的 R 代码中查询 foo 的 x 值?

make.foo <- function() {
x <- 123
function() x * 3
}

foo <- make.foo()

# now get foo's x

最佳答案

一个函数会有一个环境

来自 ?`function`

A closure has three components, its formals (its argument list), its body (expr in the ‘Usage’ section) and its environment which provides the enclosure of the evaluation frame when the closure is used.

因此您可以从该环境中获取(或使用ls 列出对象)

get('x', envir = environment(foo))
## [1] 123

或者如果你想知道环境中的所有对象

ls(envir = environment(foo))
## 'x'

如果你想分配给那个环境(即改变x)

assign('x', 24, envir = environment(foo))

foo()
## 72

你甚至可以将它从环境中移除

rm(x, envir = environment(foo))
foo()
## Error in foo() : object 'x' not found

然后使用全局分配的x

x <- 3
foo()
# [1] 9

并重新分配给函数的环境

assign('x', 123, envir = environment(foo))
foo()
## [1] 369

关于r - 如何在 R 的闭包中查询符号的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12634012/

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