ねこすたっと

ねこの気持ちと統計について悩む筆者の備忘録的ページ。

量的変数をカテゴリー化する(cut関数)[R]

ここでは71羽のニワトリについて、エサ(6種類)と体重のデータを使う。
連続変数のweightをカテゴリー化する。

> data(chickwts)
> head(chickwts, 3)
  weight      feed
1    179 horsebean
2    160 horsebean
3    136 horsebean

> summary(chickwts$weight)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
  108.0   204.5   258.0   261.3   323.5   423.0 

cut( )でN個のカテゴリーに分ける

引数breaksに1つの数値を指定する。

wt_cat1 <- cut(weight, breaks = 3)
> table(wt_cat1)
wt_cat1
(108,213] (213,318] (318,423] 
       20        31        20 

ヘルプによると

When breaks is specified as a single number, the range of the data is divided into breaks pieces of equal length, and then the outer limits are moved away by 0.1% of the range to ensure that the extreme values both fall within the break intervals. (If x is a constant vector, equal-length intervals are created, one of which includes the single value.)

とあるので、だいたい同じ数になるように分割した後、極端な値は取り除かれるみたい。

cut( )で境界値を指定して分ける

引数breaksに境界値をベクトルで指定する。
以下注意事項:

  • 両端を指定する必要があるので、N個のカテゴリーに分けるときは(N+1)個の境界値が必要。
  • 上下限を指定しないときはinfを使う。
  • right=FALSEとすると「〜以上〜未満」のように右端を含まない。
  • 引数labelsでカテゴリー名を指定できる。
wt_cat2 <- cut(weight, 
               breaks = c("-inf",200,300,"inf"),
               labels = c("wt100","wt200","wt300over"),
               right=FALSE)
> table(wt_cat2)
wt_cat2
    wt100     wt200 wt300over 
       17        28        26 

カテゴリー名を整数値にしたい

引数labels=FALSEとする。

wt_cat3 <- cut(weight, 
               breaks = c("-inf",200,300,"inf"),
               labels = FALSE,
               right=FALSE)
> table(wt_cat3)
wt_cat3
 1  2  3 
17 28 26 

もしくはfindInterval()を使う(こっちの方が効率が良いらしい)。

wt_cat4 <- findInterval(weight,
                        vec= c("-inf",200,300,"inf"))

結果は割愛。

おわりに

  • 特に探索的に傾向を見る目的でカテゴリー化するときはcut()は便利だと思う
  • ジャクソン・ギャラクシーの猫の手懐け方はホントにすごいと思う