通过玩弄R中的一个函数,我发现它有更多的方面,而不是满足眼睛。什么/哪里是一个函数对象的属性?
考虑的部份简单的功能分配,直接在控制台输入:
f <- function(x)x^2
通常的“属性”的f
,在广义上,是(i)的正式参数列表,(二)身体表达和(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'元素,而不是很多我不知道的东西,你可能想要锻炼那个语句。 – 2013-04-09 19:54:11
@CarlWitthoft,我尝试使用具有不同于'R_GlobalEnv'环境的函数的'attributes(f)< - NULL'(并且实际上在其外壳中查找符号),它仍然有效。另外,使用'body <-'会自动从其属性中剥离函数。考虑到下面的Josh的回答,甚至有一个选项可以从头开始保留这些属性。你能提出另一个需要属性的测试吗? – 2013-04-10 03:09:15