【发布时间】:2013-04-09 18:48:02
【问题描述】:
通过在 R 中玩弄一个函数,我发现它的方面比我看到的要多。
考虑一下简单的函数分配,直接在控制台中输入:
f <- function(x)x^2
f 的通常“属性”在广义上是 (i) 形式参数列表,(ii) 主体表达式和 (iii) 将成为函数评估框架的外壳的环境.可通过以下方式访问它们:
> formals(f)
$x
> body(f)
x^2
> environment(f)
<environment: R_GlobalEnv>
此外,str 返回更多附加到f 的信息:
> str(f)
function (x)
- attr(*, "srcref")=Class 'srcref' atomic [1:8] 1 6 1 19 6 19 1 1
.. ..- attr(*, "srcfile")=Classes 'srcfilecopy', 'srcfile' <environment: 0x00000000145a3cc8>
让我们尝试联系他们:
> attributes(f)
$srcref
function(x)x^2
这是作为文本打印的,但它存储为数字向量:
> c(attributes(f)$srcref)
[1] 1 6 1 19 6 19 1 1
而且这个对象也有自己的属性:
> attributes(attributes(f)$srcref)
$srcfile
$class
[1] "srcref"
第一个是环境,有3个内部对象:
> mode(attributes(attributes(f)$srcref)$srcfile)
[1] "environment"
> ls(attributes(attributes(f)$srcref)$srcfile)
[1] "filename" "fixedNewlines" "lines"
> attributes(attributes(f)$srcref)$srcfile$filename
[1] ""
> attributes(attributes(f)$srcref)$srcfile$fixedNewlines
[1] TRUE
> attributes(attributes(f)$srcref)$srcfile$lines
[1] "f <- function(x)x^2" ""
你来了!这是 R 用来打印 attributes(f)$srcref 的字符串。
所以问题是:
是否有任何其他对象链接到
f?如果有,如何联系他们?如果我们去掉
f的属性,使用attributes(f) <- NULL,它似乎不会影响功能。这样做有什么缺点吗?
【问题讨论】:
-
我对您的#2 声明高度怀疑。除非你已经解决了剥离函数的填充问题,包括间接环境调用、修改其
body元素,以及很多我不知道的东西,否则你可能想要缓和该声明。 -
@CarlWitthoft,我尝试将
attributes(f) <- NULL与具有不同于R_GlobalEnv的环境的函数一起使用(实际上在其外壳中查找符号),它仍然有效。此外,使用body<-会自动将函数从其属性中剥离。考虑到 Josh 在下面的回答,甚至可以选择从一开始就将这些属性保持为空。你能提出另一个需要属性的测试吗?