通过使用 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,它似乎不会影响功能。这样做有什么缺点吗?