以前にもシミュレーションで使っている手技たが一度まとめておこうと思う。
55点が平均で標準偏差15程度のテストっぽい仮想データを作成する。
set.seed(123) # 乱数シードの固定 d1 <- data.frame(rnorm(100, mean=55, sd= 15)) # 100個のデータの作成 d1 <- round(d1) # まるめ(四捨五入で整数値に) summary(d1)
最小値が20点で、最高点が88点で、平均が56.42点である。
Show in New WindowClear OutputExpand/Collapse Output rnorm.100..mean...55..sd...15. Min. :20.00 1st Qu.:47.75 Median :56.00 Mean :56.42 3rd Qu.:65.25 Max. :88.00
cut関数を使用する
4分位で分ける。データは整数型で出力される。
d2 <- lapply(d1, function(x){ cut(x, breaks=quantile(x), include.lowest=TRUE, ordered=TRUE, labels= FALSE) }) str(d2) table(d2)
2分位(中央値)で分ける。
d3 <- lapply(d1, function(x){ cut(x, breaks=quantile(x, prob = seq(0, 1, length = 3)), include.lowest=TRUE, ordered=TRUE, labels= FALSE) }) str(d3) table(d3)
OneRパッケージを使用する
4分位で分ける。OneRパッケージは因子型で出力される。
library(OneR) d4 <- bin(d1, nbins = 4, labels = c(1,2,3,4), method = "content") str(d4) table(d4)
整数型で利用する際には変換が必要だ。
library(dplyr) d4 <- d4 %>% mutate_if(is.factor, as.integer) # 整数型への変換
2分位(中央値)で分ける。
library(OneR) d5 <- bin(d1, nbins = 2, labels = c(1,2), method = "content") str(d5) table(d5)
cut関数を使うのが標準的だが、プログラムっぽさが出てくるのて嫌がる人もでてきそうな気がする。
OneRパッケージだとパッケージのインストールの手間などはあるが、プログラムっぽくないのが利点だろうか。