Rが理解しやすい表
- スタック形式でつくると利用しやすい
- 人間向けの表とはちがうんだなー、と覚えておく。
ヒト向けの表
クラス1 |
生徒 |
数学 |
化学 |
国語 |
英語 |
A |
85 |
70 |
55 |
61 |
B |
46 |
83 |
60 |
77 |
C |
58 |
94 |
84 |
61 |
D |
90 |
79 |
51 |
63 |
E |
76 |
56 |
66 |
61 |
F |
59 |
32 |
49 |
52 |
G |
73 |
79 |
78 |
83 |
H |
65 |
86 |
71 |
95 |
I |
88 |
90 |
63 |
42 |
J |
61 |
67 |
59 |
71 |
- クラス1のAさんが受けた教科のうち数学の点数は85点
- 点数85の情報ラベルは分散して表現されている
- 人間にわかりやすいけどRは不得意
- Rではwideと表現される
Rむけの表:スタック形式
クラス |
生徒 |
教科 |
得点 |
1 |
A |
数学 |
85 |
1 |
A |
化学 |
70 |
1 |
A |
国語 |
55 |
1 |
A |
英語 |
61 |
1 |
B |
数学 |
46 |
1 |
B |
化学 |
83 |
1 |
B |
国語 |
60 |
1 |
B |
英語 |
77 |
1 |
C |
数学 |
58 |
... |
... |
... |
... |
- 縦方向は常に同じカテゴリ、同じ単位の値
- 横方向は常に同じデータポイント(ここでは生徒)
- クラス1のAさんが受けた教科のうち数学の点数は85点、が一列に並んでいる
- 人間には見にくいけど、Rには分かりやすい
- Rではlongと表現される
ヒト向きの表からR向きの表への変換
- うっかり人間用の表で集計してしまったとき。
- stack()をつかう。
student<-LETTERS[1:10]
math.test<-c(85,46,58,90,76,59,73,65,88,61)
chem.test<-c(70,83,94,79,56,32,79,86,90,67)
dat<-data.frame(student,math=math.test,chem=chem.test)
dat
dat.stack<-stack(dat,select=c(math,chem))
dat.stack
dat2<-data.frame(student=rep(dat$student,2),
subject=dat.stack$ind,
score=dat.stack$values)
dat2
- エクセルで集計した表は、CSV形式で保存して、read.csv()で読み込む。
Rむきの表をヒト向きの表に変換する
- reshape()を使う
- directionにwideを、idvarに縦方向に並べたいベクトル名、timevarに横方向に並べたいベクトル名を指定する。残りのベクトルがtimevarに応じて分割される。
- データ表に3変数以上がある場合、指定がわかりづらい。いろいろ試行錯誤するしかない。
student<-LETTERS[1:10]
math.test<-c(85,46,58,90,76,59,73,65,88,61)
chem.test<-c(70,83,94,79,56,32,79,86,90,67)
dat<-data.frame(student,math=math.test,chem=chem.test)
dat.stack<-stack(dat,select=c(math,chem))
dat2<-data.frame(student=rep(dat$student,2),
subject=dat.stack$ind,
score=dat.stack$values)
dat2
dat3<-reshape(dat2, idvar="student", timevar="subject",
direction="wide")
dat3