2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

R の attach 関数について

Posted at

はじめに

R のattach関数の操作方法についてまとめた。使うデータについてはこちらの記事を参考に。df というdata.frame型の変数に1000人分の性別、身長、体重、血液型のデータがある状況でattach 関数の挙動を見ていく。

attach関数

attach関数でデータフレームを展開する前は、名前を$で項目名を指定しなければ値にアクセスできない。

> str(df)
'data.frame':	1000 obs. of  4 variables:
 $ SEX   : chr  "male" "male" "female" "male" ...
 $ HEIGHT: num  179 165 170 163 176 ...
 $ WEIGHT: num  94.2 82.5 63 64.8 93.2 ...
 $ BLOOD : chr  "A" "A" "A" "A" ...
> head(HEIGHT)
 head(HEIGHT) でエラー:  オブジェクト 'HEIGHT' がありません 
> head(df$HEIGHT)
[1] 179.0543 164.8774 170.4041 163.3607 176.0256 181.1941

これをattach関数で展開すると…、

> attach(df)
> head(HEIGHT)
[1] 179.0543 164.8774 170.4041 163.3607 176.0256 181.1941

項目名だけで値にアクセスできるようになる。

detach関数

上記の様に df をattach関数で展開済みの状態で同じ項目名を持つ df2 というdata.frame を定義する。それを再度attachで展開しようとすると以下のようなエラーが出る。

> df2 <- data.frame(SEX="male", HEIGHT=171.5068, WEIGHT=74.5213, BLOOD="B")
> df2
   SEX   HEIGHT  WEIGHT BLOOD
1 male 171.5068 74.5213     B
> attach(df2)
 以下のオブジェクトは df (pos = 3) からマスクされています: 

     BLOOD, HEIGHT, SEX, WEIGHT 

変数名が被ってしまっているので、当然エラーとなる。一度展開した df を解除し、 df2 の項目名を展開したい場合は以下の様にする。

> detach(df)
> HEIGHT
 エラー:  オブジェクト 'HEIGHT' がありません 
> attach(df2)
> HEIGHT
[1] 171.5068

おわりに

attach, detach関数の使い方をまとめた。全部をリセットしたければdetach関数を使うより、R 自体を再起動してしまう方が手っ取り早そうではある。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?