備忘ログ

チラシの裏的備忘録&メモ

Rで出力した結果をオブジェクトに保存し忘れたときに使う.Last.Value

Rで出力した結果をオブジェクトに保存し忘れて悲しい気持ちになることがあります(!?)が、Rは最後に出力した結果を.Last.Valueという隠しオブジェクトにしまっておいてくれます。

正確には

Description The value of the internal evaluation of a top-level R expression is always assigned to .Last.value (in package:base) before further processing (e.g., printing). (Last.value {base} R Documentation)

とのことでbaseパッケージの.Last.Valueに実行した式の評価結果が標準出力前の状態で格納されている様子。

なので

oneway.test(Orange$circumference~Orange$Tree)

    One-way analysis of means (not assuming equal
    variances)

data:  Orange$circumference and Orange$Tree
F = 0.77844, num df = 4.000, denom df = 14.835,
p-value = 0.5565

.Last.value

    One-way analysis of means (not assuming equal
    variances)

data:  Orange$circumference and Orange$Tree
F = 0.77844, num df = 4.000, denom df = 14.835,
p-value = 0.5565

で、$で取り出したい値を指定できる。

.Last.value$p.value
[1] 0.556485
x <- .Last.value$p.value
x
[1] 0.556485

入れたい値だけを取り出してオブジェクトに代入できる。

ただし、

oneway.test(Orange$circumference~Orange$Tree)$p.value
[1] 0.556485
.Last.value
[1] 0.556485

ということで、取り出したい値を選んで式を作って実行していると、.Last.Valueに残っている値は取り出された値になってしまうので、他の値が必要になったときには再計算が必要になる。

んで、

Details The value of a top-level assignment is put in .Last.value, unlike S.

Do not assign to .Last.value in the workspace, because this will always mask the object of the same name in package:base. (Last.value {base} R Documentation)

とあるので.Last.Valueに誤って任意で代入しないようにと注意喚起されている。

.から始まる隠しオブジェクトにあえて代入することなんてないと思うけどね。

次の式を実行するとその結果に.Last.Valueが置き換わる。

でかい計算式や内容を見てからオブジェクトに保存したいと思ったら使えるかも。