1.将factor类型的数据进行哑变量处理。
> custome
id gender mood outcom
1 10 male happy 1
2 20 female sad 1
3 30 female happy 0
4 40 male sad 0
5 50 female happy 0
需要加载包caret.之后利用dummyVars函数进行处理。
> dmy<-dummyVars("~.",data=custome)
> trsf<-data.frame(predict(dmy,newdata=custome))
> trsf
id gender.female gender.male mood.happy mood.sad outcom
1 10 0 1 1 0 1
2 20 1 0 0 1 1
3 30 1 0 1 0 0
4 40 0 1 0 1 0
5 50 1 0 1 0 0
又如,对鸢尾花数据集进行处理。可以看到最后一列是factor类型。(假若不是factor类型,需要使用as.factor 进行转换)
> 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