統計Rの勉強-R intro 4章

前々回前回に続き、R introを読む。

4章は、factorの使い方

  • factorはカテゴリごとの情報をまとめたもの。
  • これを使うと簡単なカテゴリごとの統計処理ができる。
  • facotr(vectorオブジェクト)関数:factorオブジェクトを作る
  • levels(factorオブジェクト)関数:factorオブジェクトのカテゴリ一覧を表示
  • tapply関数:vectorオブジェクトのfactorオブジェクト内のカテゴリごとに、任意の関数を適用する。
                    • -

4章 Ordered and unordered factors
factorはベクトルオブジェクトで、同じ長さを持つ別のベクトルのグループ化で使う。
順序付きと順序なしがある。

#30人の州名と収入
state  <-  c("tas",  "sa",    "qld",  "nsw",  "nsw",  "nt",    "wa",    "wa",
"qld",  "vic",  "nsw",  "vic",  "qld",  "qld",  "sa",    "tas",
"sa",    "nt",    "wa",    "vic",  "qld",  "nsw",  "nsw",  "wa",
"sa",    "act",  "nsw",  "vic",  "vic",  "act")
incomes  <-  c(60,  49,  40,  61,  64,  60,  59,  54,  62,  69,  70,  42,  56,
61,  61,  61,  58,  51,  48,  65,  49,  49,  41,  48,  52,  46,
59,  46,  58,  43)
#州ごとのfactorオブジェクト作成
statef  <-  factor(state)
#水準:州のuniq名
levels(statef)
#州ごとの平均収入
incmeans  <-  tapply(incomes,  statef,  mean)
#州ごとの誤差
stderr  <-  function(x)  sqrt(var(x)/length(x))
incster  <-  tapply(incomes,  statef,  stderr)
#factorオブジェクトのカテゴリ順序あり版
statef  <-  ordered(state)

これだけだとなんとなくよくわからないので、ヘルプを見てみる。
factor関数は、実際にはカテゴリ一覧も引数にとることができる。つまり、計算したいベクトルから自動的にカテゴリを作るだけじゃない。
たとえば、各文字でカウントしたい場合、0回の文字もあるはずなので、levelsに追加。

str <- substring("statistics", 1:10, 1:10)
strf <- factor(str, levels=letters)
strc <- tapply(str, strf, length)
strc[is.na(strc)]<-0
strc