gpt4 book ai didi

r - 什么是R的父框架

转载 作者:行者123 更新时间:2023-12-04 05:38:10 25 4
gpt4 key购买 nike

R的父框架是什么。顺便说一句,父框架是什么意思?我猜这是定义环境而不是调用环境,因为R使用词法作用域,但是我不确定。谢谢。

最佳答案

好吧,从?parent.frame帮助页面

The parent frame of a function evaluation is the environment in which the function was called. It is not necessarily numbered one less than the frame number of the current evaluation, nor is it the environment within which the function was defined. sys.parent returns the number of the parent frame if n is 1 (the default), the grandparent if n is 2, and so on



并且

Strictly, sys.parent and parent.frame refer to the context of the parent interpreted function. So internal functions (which may or may not set contexts and so may or may not appear on the call stack) may not be counted, and S3 methods can also do surprising things.



因此parent.frame是指从中调用函数的环境,而不是定义它的环境。

例如
parentls <- function() {
ls(envir=parent.frame())
}

a<-function() {
x <- 5
parentls()
}

b <- function() {
z <- 10
parentls()
}

a()
# [1] "x"
b()
# [1] "z"
parentls()
# [1] "a" "b" "parentls"

在这里, parentls()在parent.frame中执行一个 ls()。从 a()b()内部运行时,我们只能看到这些函数中的变量。当单独调用它时,它只是为您提供了全局环境中的所有变量,就好像您自己调用了 ls()一样。

您可以在Hadely的Advanced R的 Closure sectionCalling Environment section中阅读有关父框架的更多信息。

关于r - 什么是R的父框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28641395/

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