caretパッケージのdummyVarsによるダミー変数の作り方
(2015.06.23更新)dummiesパッケージの方が簡単なので追記しとく
weda_654 on Twitter: "先日のLTをアップロードさせていただきます。 #TokyoR http://t.co/IUlNFgthdW"
以下オリジナル
カテゴリカル変数からダミー変数を作成する際、"caretパッケージのdummyVarsが便利"ということで作り方をメモしとく。
数値変数・カテゴリカル変数まとめて突っ込んでもカテゴリカル変数だけ処理してくれる。
> library(caret) > data(iris) > str(iris) 'data.frame': 150 obs. of 5 variables: $ Sepal.Length: num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ... $ Sepal.Width : num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ... $ Petal.Length: num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ... $ Petal.Width : num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ... $ Species : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ... > noNames <- dummyVars(~., data=iris) > iris.dummy <- as.data.frame(predict(noNames, iris)) > str(iris.dummy) 'data.frame': 150 obs. of 7 variables: $ Sepal.Length : num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ... $ Sepal.Width : num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ... $ Petal.Length : num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ... $ Petal.Width : num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ... $ Species.setosa : num 1 1 1 1 1 1 1 1 1 1 ... $ Species.versicolor: num 0 0 0 0 0 0 0 0 0 0 ... $ Species.virginica : num 0 0 0 0 0 0 0 0 0 0 ...
カテゴリカル変数の組み合わせでダミー変数を作成する場合は以下のようにする。
> tmp.titanic <- data.frame(Titanic) # サンプルデータ作成 > titanic <- data.frame( + Class = rep(tmp.titanic$Class, tmp.titanic$Freq), + Sex = rep(tmp.titanic$Sex, tmp.titanic$Freq), + Age = rep(tmp.titanic$Age, tmp.titanic$Freq), + Survived = rep(tmp.titanic$Survived, tmp.titanic$Freq) + ) > str(titanic) 'data.frame': 2201 obs. of 4 variables: $ Class : Factor w/ 4 levels "1st","2nd","3rd",..: 3 3 3 3 3 3 3 3 3 3 ... $ Sex : Factor w/ 2 levels "Male","Female": 1 1 1 1 1 1 1 1 1 1 ... $ Age : Factor w/ 2 levels "Child","Adult": 1 1 1 1 1 1 1 1 1 1 ... $ Survived: Factor w/ 2 levels "No","Yes": 1 1 1 1 1 1 1 1 1 1 ... # SexとAgeの組み合わせでダミー変数を作成 > noNames <- dummyVars(~Class+Sex:Age+Survived, data=titanic) > titanic.dummy <- as.data.frame(predict(noNames, titanic)) > str(titanic.dummy) 'data.frame': 2201 obs. of 10 variables: $ Class.1st : num 0 0 0 0 0 0 0 0 0 0 ... $ Class.2nd : num 0 0 0 0 0 0 0 0 0 0 ... $ Class.3rd : num 1 1 1 1 1 1 1 1 1 1 ... $ Class.Crew : num 0 0 0 0 0 0 0 0 0 0 ... $ Survived.No : num 1 1 1 1 1 1 1 1 1 1 ... $ Survived.Yes : num 0 0 0 0 0 0 0 0 0 0 ... $ Sex.Male:Age.Child : num 1 1 1 1 1 1 1 1 1 1 ... $ Sex.Female:Age.Child: num 0 0 0 0 0 0 0 0 0 0 ... $ Sex.Male:Age.Adult : num 0 0 0 0 0 0 0 0 0 0 ... $ Sex.Female:Age.Adult: num 0 0 0 0 0 0 0 0 0 0 ...
重回帰などで使用する際はこのままだと多重共線性が生じるのでダミー変数の数は水準数-1にする必要がある。