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 が print に使用する文字列attributes(f)$srcref
です。
質問は次のとおりです。
にリンクされている他のオブジェクトはあります
f
か? もしそうなら、彼らに到達する方法は?f
を使用してその属性を取り除いattributes(f) <- NULL
ても、関数には影響しないようです。これを行うことの欠点はありますか?