2

I run the following code

sapply( 0:3, function(x){ls(envir = sys.frame(x))} )

And get the following result

[[1]]
[1] "mat"         "mat_inverse"

[[2]]
[1] "FUN"       "simplify"  "USE.NAMES" "X"        

[[3]]
[1] "FUN" "X"  

[[4]]
[1] "x"

It seems like it lists all the objects in the current enclosing environment; I do have mat and mat_inverse as two variables. But I am not sure what it returns for [[2]], [[3]], [[4]]. Is there a way to debug this code to track what this code does? Especially the following part:

envir = sys.frame(x)

is very confusing to me.

4

1 回答 1

4

sys.frame允许您返回调用堆栈。sys.frame(0)是堆栈的开始(可以说是您的初始工作区)。sys.frame(1)嵌套一层深,sys.frame(2)嵌套两层深等。

这段代码很好地演示了调用sapply. 它经过四个环境(编号 0-3)并打印每个环境中的对象。sapply实际上是lapply. 当您实际调用此代码时,您会得到什么环境?

环境 0 是开始,即您的整个工作区。环境 1 是sapply. 键入sapply以查看其代码。您会看到函数头有simplify,这是您在 [[2]] 中看到的变量之一。环境 2 是lapply. 再次键入lapply以查看其代码;函数头包含FUNX。环境 3 是您定义的sapply要运行的函数。它只有一个变量,x

作为实验,运行

sapply(0:3, function(x) { howdy = 5; ls(envir = sys.frame(x)) } )

最后一行将更改为,因为您在最终环境中定义了一个新变量(内部[1] "howdy" "x"函数)。lapplysapply

于 2013-10-03T21:14:15.153 回答