getwd()
## [1] "C:/data/3일차"
setwd("C:/data")
library(dplyr)
## 
## 다음의 패키지를 부착합니다: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
#caret::createDataPartition(y,time=1,p=0.5,list=TRUE)

set.seed(1)
data(iris)
library(caret)
## 필요한 패키지를 로딩중입니다: ggplot2
## 필요한 패키지를 로딩중입니다: lattice
idx<-createDataPartition(iris$Species,p=0.8)
idx$Resample1
##   [1]   1   3   4   6   7   8   9  10  12  14  15  18  19  20  21  22  23  24
##  [19]  25  26  27  29  31  32  33  34  35  36  37  38  39  40  41  42  43  45
##  [37]  46  47  48  49  51  52  53  56  57  59  60  61  62  63  64  66  67  68
##  [55]  69  70  72  73  74  75  76  77  78  82  83  84  85  86  87  88  89  90
##  [73]  91  92  93  95  96  97  99 100 101 102 103 105 106 107 109 110 111 112
##  [91] 114 115 116 117 119 120 122 124 125 126 127 128 129 130 131 132 133 134
## [109] 135 136 137 138 139 140 142 143 145 146 147 149
table(iris[idx$Resample1,"Species"])
## 
##     setosa versicolor  virginica 
##         40         40         40
table(iris[-idx$Resample1,"Species"])
## 
##     setosa versicolor  virginica 
##         10         10         10
idx<-createDataPartition(iris$Species,p=0.8,list=FALSE)
train<-iris[idx,]
test<-iris[-idx,]
nrow(train)
## [1] 120
nrow(test)
## [1] 30
set.seed(2)
data(iris)
idx<-createDataPartition(iris$Species,p=0.6,list=FALSE)
train<-iris[idx,]
valid_test<-iris[-idx,]
idx2<-createDataPartition(valid_test$Species,p=0.5,list=FALSE)
valid<-valid_test[idx2,]
test<-valid_test[-idx2,]
nrow(train)/nrow(iris)
## [1] 0.6
nrow(valid)/nrow(iris)
## [1] 0.2
nrow(test)/nrow(iris)
## [1] 0.2
zs_iris<-preProcess(iris,method=c("center","scale"))
zs_iris
## Created from 150 samples and 5 variables
## 
## Pre-processing:
##   - centered (4)
##   - ignored (1)
##   - scaled (4)
zs_iris_p<-predict(zs_iris,iris)

#install.packages("psych")
library(psych)
## 
## 다음의 패키지를 부착합니다: 'psych'
## The following objects are masked from 'package:ggplot2':
## 
##     %+%, alpha
describe(zs_iris_p[,1:4])
##              vars   n mean sd median trimmed  mad   min  max range  skew
## Sepal.Length    1 150    0  1  -0.05   -0.04 1.25 -1.86 2.48  4.35  0.31
## Sepal.Width     2 150    0  1  -0.13   -0.03 1.02 -2.43 3.08  5.51  0.31
## Petal.Length    3 150    0  1   0.34    0.00 1.05 -1.56 1.78  3.34 -0.27
## Petal.Width     4 150    0  1   0.13   -0.02 1.36 -1.44 1.71  3.15 -0.10
##              kurtosis   se
## Sepal.Length    -0.61 0.08
## Sepal.Width      0.14 0.08
## Petal.Length    -1.42 0.08
## Petal.Width     -1.36 0.08
data(iris)
sca_iris<-preProcess(iris,method="range")
sca_iris_p<-predict(sca_iris,iris)
head(sca_iris_p)
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1   0.22222222   0.6250000   0.06779661  0.04166667  setosa
## 2   0.16666667   0.4166667   0.06779661  0.04166667  setosa
## 3   0.11111111   0.5000000   0.05084746  0.04166667  setosa
## 4   0.08333333   0.4583333   0.08474576  0.04166667  setosa
## 5   0.19444444   0.6666667   0.06779661  0.04166667  setosa
## 6   0.30555556   0.7916667   0.11864407  0.12500000  setosa
describe(sca_iris_p)
##              vars   n mean   sd median trimmed  mad min max range  skew
## Sepal.Length    1 150 0.43 0.23   0.42    0.42 0.29   0   1     1  0.31
## Sepal.Width     2 150 0.44 0.18   0.42    0.43 0.19   0   1     1  0.31
## Petal.Length    3 150 0.47 0.30   0.57    0.47 0.31   0   1     1 -0.27
## Petal.Width     4 150 0.46 0.32   0.50    0.45 0.43   0   1     1 -0.10
## Species*        5 150 2.00 0.82   2.00    2.00 1.48   1   3     2  0.00
##              kurtosis   se
## Sepal.Length    -0.61 0.02
## Sepal.Width      0.14 0.01
## Petal.Length    -1.42 0.02
## Petal.Width     -1.36 0.03
## Species*        -1.52 0.07
data(iris)
bc_iris = preProcess(iris, method = "BoxCox")
bc_iris
## Created from 150 samples and 5 variables
## 
## Pre-processing:
##   - Box-Cox transformation (4)
##   - ignored (1)
## 
## Lambda estimates for Box-Cox transformation:
## -0.1, 0.3, 0.9, 0.6
bc_iris_t = predict(bc_iris, iris)
head(bc_iris_t)
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1     1.629241    1.520660          1.4  -1.0321154  setosa
## 2     1.589235    1.301297          1.4  -1.0321154  setosa
## 3     1.547563    1.391905          1.3  -1.0321154  setosa
## 4     1.526056    1.347113          1.5  -1.0321154  setosa
## 5     1.609438    1.561856          1.4  -1.0321154  setosa
## 6     1.686399    1.680826          1.7  -0.7048667  setosa
par(mfrow=c(1,2))
plot(density(x=iris$Sepal.Width))
plot(density(x=bc_iris_t$Sepal.Width))

data(iris)
pca_iris<-preProcess(iris,method="pca")
pca_iris
## Created from 150 samples and 5 variables
## 
## Pre-processing:
##   - centered (4)
##   - ignored (1)
##   - principal component signal extraction (4)
##   - scaled (4)
## 
## PCA needed 2 components to capture 95 percent of the variance
pca_iris_p<-predict(pca_iris,iris)
head(pca_iris_p)
##   Species       PC1        PC2
## 1  setosa -2.257141 -0.4784238
## 2  setosa -2.074013  0.6718827
## 3  setosa -2.356335  0.3407664
## 4  setosa -2.291707  0.5953999
## 5  setosa -2.381863 -0.6446757
## 6  setosa -2.068701 -1.4842053
#install.packages("earth")
library(earth)
## 필요한 패키지를 로딩중입니다: Formula
## 필요한 패키지를 로딩중입니다: plotmo
## 필요한 패키지를 로딩중입니다: plotrix
## 
## 다음의 패키지를 부착합니다: 'plotrix'
## The following object is masked from 'package:psych':
## 
##     rescale
## 필요한 패키지를 로딩중입니다: TeachingDemos
data(etitanic)
library(dplyr)
glimpse(etitanic)
## Rows: 1,046
## Columns: 6
## $ pclass   <fct> 1st, 1st, 1st, 1st, 1st, 1st, 1st, 1st, 1st, 1st, 1st, 1st, 1…
## $ survived <int> 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1…
## $ sex      <fct> female, male, female, male, female, male, female, male, femal…
## $ age      <dbl> 29.0000, 0.9167, 2.0000, 30.0000, 25.0000, 48.0000, 63.0000, …
## $ sibsp    <int> 0, 1, 1, 1, 1, 0, 1, 0, 2, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1…
## $ parch    <int> 0, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1…
dummies <- dummyVars(survived ~ ., data = etitanic)
dummies
## Dummy Variable Object
## 
## Formula: survived ~ .
## 6 variables, 2 factors
## Variables and levels will be separated by '.'
## A less than full rank encoding is used
data(airquality)
colSums(is.na(airquality))
##   Ozone Solar.R    Wind    Temp   Month     Day 
##      37       7       0       0       0       0
#install.packages("RANN")
library(RANN)
knn_im<-preProcess(airquality[1:4],method="knnImpute")
head(predict(knn_im,airquality))
##         Ozone     Solar.R       Wind       Temp Month Day
## 1 -0.03423409  0.04517615 -0.7259482 -1.1497140     5   1
## 2 -0.18580489 -0.75430487 -0.5556388 -0.6214670     5   2
## 3 -0.91334473 -0.41008388  0.7500660 -0.4101682     5   3
## 4 -0.73145977  1.41095624  0.4378323 -1.6779609     5   4
## 5 -0.69508278 -0.92308420  1.2326091 -2.3118573     5   5
## 6 -0.42831817 -0.28349938  1.4029185 -1.2553634     5   6
knn_im_p<-predict(knn_im,airquality)
colSums(is.na(knn_im_p))
##   Ozone Solar.R    Wind    Temp   Month     Day 
##       0       0       0       0       0       0
describe(knn_im_p)
##         vars   n  mean   sd median trimmed   mad   min   max range  skew
## Ozone      1 153 -0.04 0.92  -0.31   -0.16  0.72 -1.25  3.82  5.06  1.30
## Solar.R    2 153 -0.01 0.99   0.17    0.03  1.05 -1.99  1.64  3.63 -0.39
## Wind       3 153  0.00 1.00  -0.07   -0.02  0.97 -2.34  3.05  5.39  0.34
## Temp       4 153  0.00 1.00   0.12    0.04  0.94 -2.31  2.02  4.33 -0.37
## Month      5 153  6.99 1.42   7.00    6.99  1.48  5.00  9.00  4.00  0.00
## Day        6 153 15.80 8.86  16.00   15.80 11.86  1.00 31.00 30.00  0.00
##         kurtosis   se
## Ozone       1.62 0.07
## Solar.R    -0.99 0.08
## Wind        0.03 0.08
## Temp       -0.46 0.08
## Month      -1.32 0.11
## Day        -1.22 0.72
median_im<-preProcess(airquality[1:4],method="medianImpute")
head(predict(median_im,airquality))
##   Ozone Solar.R Wind Temp Month Day
## 1  41.0     190  7.4   67     5   1
## 2  36.0     118  8.0   72     5   2
## 3  12.0     149 12.6   74     5   3
## 4  18.0     313 11.5   62     5   4
## 5  31.5     205 14.3   56     5   5
## 6  28.0     205 14.9   66     5   6
library(caret)
library(mlbench)
data("Soybean")
head(nearZeroVar(Soybean, saveMetrics=TRUE))
##             freqRatio percentUnique zeroVar   nzv
## Class        1.010989     2.7818448   FALSE FALSE
## date         1.137405     1.0248902   FALSE FALSE
## plant.stand  1.208191     0.2928258   FALSE FALSE
## precip       4.098214     0.4392387   FALSE FALSE
## temp         1.879397     0.4392387   FALSE FALSE
## hail         3.425197     0.2928258   FALSE FALSE
nearZeroVar(Soybean)
## [1] 19 26 28
mySoybean <- Soybean[, -nearZeroVar(Soybean)]

data(mdrr)
dim(mdrrDescr)
## [1] 528 342
nzv <- nearZeroVar(mdrrDescr)
filteredDescr <- mdrrDescr[, -nzv]
dim(filteredDescr)
## [1] 528 297
descrCor<-cor(filteredDescr)
highlyCorDescr <- findCorrelation(descrCor, cutoff = 0.75)
filteredDescr <- filteredDescr[, -highlyCorDescr]
#caret::featurePlot(x,y,plot=if(is.factor(y)) "strip" else "scatter")

library(mlbench)
data(BostonHousing)
x=BostonHousing[,c("age", "lstat", "tax")]
y=BostonHousing$medv
featurePlot(x,y = BostonHousing$medv,plot = "scatter",layout = c(3, 1))

data("PimaIndiansDiabetes")
glimpse(PimaIndiansDiabetes)
## Rows: 768
## Columns: 9
## $ pregnant <dbl> 6, 1, 8, 1, 0, 5, 3, 10, 2, 8, 4, 10, 10, 1, 5, 7, 0, 7, 1, 1…
## $ glucose  <dbl> 148, 85, 183, 89, 137, 116, 78, 115, 197, 125, 110, 168, 139,…
## $ pressure <dbl> 72, 66, 64, 66, 40, 74, 50, 0, 70, 96, 92, 74, 80, 60, 72, 0,…
## $ triceps  <dbl> 35, 29, 0, 23, 35, 0, 32, 0, 45, 0, 0, 0, 0, 23, 19, 0, 47, 0…
## $ insulin  <dbl> 0, 0, 0, 94, 168, 0, 88, 0, 543, 0, 0, 0, 0, 846, 175, 0, 230…
## $ mass     <dbl> 33.6, 26.6, 23.3, 28.1, 43.1, 25.6, 31.0, 35.3, 30.5, 0.0, 37…
## $ pedigree <dbl> 0.627, 0.351, 0.672, 0.167, 2.288, 0.201, 0.248, 0.134, 0.158…
## $ age      <dbl> 50, 31, 32, 21, 33, 30, 26, 29, 53, 54, 30, 34, 57, 59, 51, 3…
## $ diabetes <fct> pos, neg, pos, neg, pos, neg, pos, neg, pos, pos, neg, pos, n…
#PimaIndiansDiabetes %>% count(diabetes)

#install.packages("randomForest")
library(randomForest)
## randomForest 4.7-1.1
## Type rfNews() to see new features/changes/bug fixes.
## 
## 다음의 패키지를 부착합니다: 'randomForest'
## The following object is masked from 'package:psych':
## 
##     outlier
## The following object is masked from 'package:ggplot2':
## 
##     margin
## The following object is masked from 'package:dplyr':
## 
##     combine
control<-trainControl(method = "repeatedcv",number=5)
model<-train(diabetes~.,data=PimaIndiansDiabetes,method="rf",preProcess=c("center","scale"),trControl=control)
glimpse(model)
## List of 24
##  $ method      : chr "rf"
##  $ modelInfo   :List of 15
##   ..$ label     : chr "Random Forest"
##   ..$ library   : chr "randomForest"
##   ..$ loop      : NULL
##   ..$ type      : chr [1:2] "Classification" "Regression"
##   ..$ parameters:'data.frame':   1 obs. of  3 variables:
##   .. ..$ parameter: chr "mtry"
##   .. ..$ class    : chr "numeric"
##   .. ..$ label    : chr "#Randomly Selected Predictors"
##   ..$ grid      :function (x, y, len = NULL, search = "grid")  
##   ..$ fit       :function (x, y, wts, param, lev, last, classProbs, ...)  
##   ..$ predict   :function (modelFit, newdata, submodels = NULL)  
##   ..$ prob      :function (modelFit, newdata, submodels = NULL)  
##   ..$ predictors:function (x, ...)  
##   ..$ varImp    :function (object, ...)  
##   ..$ levels    :function (x)  
##   ..$ tags      : chr [1:4] "Random Forest" "Ensemble Model" "Bagging" "Implicit Feature Selection"
##   ..$ sort      :function (x)  
##   ..$ oob       :function (x)  
##  $ modelType   : chr "Classification"
##  $ results     :'data.frame':    3 obs. of  5 variables:
##   ..$ mtry      : num [1:3] 2 5 8
##   ..$ Accuracy  : num [1:3] 0.769 0.758 0.754
##   ..$ Kappa     : num [1:3] 0.481 0.455 0.447
##   ..$ AccuracySD: num [1:3] 0.0417 0.0457 0.0317
##   ..$ KappaSD   : num [1:3] 0.0897 0.1042 0.0724
##  $ pred        : NULL
##  $ bestTune    :'data.frame':    1 obs. of  1 variable:
##   ..$ mtry: num 2
##  $ call        : language train.formula(form = diabetes ~ ., data = PimaIndiansDiabetes, method = "rf",      preProcess = c("center", "scal| __truncated__
##  $ dots        : list()
##  $ metric      : chr "Accuracy"
##  $ control     :List of 27
##   ..$ method           : chr "repeatedcv"
##   ..$ number           : num 5
##   ..$ repeats          : num 1
##   ..$ search           : chr "grid"
##   ..$ p                : num 0.75
##   ..$ initialWindow    : NULL
##   ..$ horizon          : num 1
##   ..$ fixedWindow      : logi TRUE
##   ..$ skip             : num 0
##   ..$ verboseIter      : logi FALSE
##   ..$ returnData       : logi TRUE
##   ..$ returnResamp     : chr "final"
##   ..$ savePredictions  : chr "none"
##   ..$ classProbs       : logi FALSE
##   ..$ summaryFunction  :function (data, lev = NULL, model = NULL)  
##   ..$ selectionFunction: chr "best"
##   ..$ preProcOptions   :List of 6
##   .. ..$ thresh   : num 0.95
##   .. ..$ ICAcomp  : num 3
##   .. ..$ k        : num 5
##   .. ..$ freqCut  : num 19
##   .. ..$ uniqueCut: num 10
##   .. ..$ cutoff   : num 0.9
##   ..$ sampling         : NULL
##   ..$ index            :List of 5
##   .. ..$ Fold1.Rep1: int [1:615] 1 2 3 5 6 7 9 10 11 13 ...
##   .. ..$ Fold2.Rep1: int [1:614] 1 2 4 5 6 7 8 9 10 11 ...
##   .. ..$ Fold3.Rep1: int [1:614] 1 3 4 5 8 9 12 13 14 15 ...
##   .. ..$ Fold4.Rep1: int [1:615] 2 3 4 5 6 7 8 10 11 12 ...
##   .. ..$ Fold5.Rep1: int [1:614] 1 2 3 4 6 7 8 9 10 11 ...
##   ..$ indexOut         :List of 5
##   .. ..$ Resample1: int [1:153] 4 8 12 14 17 32 34 47 51 52 ...
##   .. ..$ Resample2: int [1:154] 3 19 23 26 39 49 50 61 71 73 ...
##   .. ..$ Resample3: int [1:154] 2 6 7 10 11 21 35 38 62 64 ...
##   .. ..$ Resample4: int [1:153] 1 9 18 22 25 30 31 33 41 44 ...
##   .. ..$ Resample5: int [1:154] 5 13 15 16 20 24 27 28 29 36 ...
##   ..$ indexFinal       : NULL
##   ..$ timingSamps      : num 0
##   ..$ predictionBounds : logi [1:2] FALSE FALSE
##   ..$ seeds            :List of 6
##   .. ..$ : int [1:3] 792145 266416 203495
##   .. ..$ : int [1:3] 850328 164040 602913
##   .. ..$ : int [1:3] 673309 56276 629330
##   .. ..$ : int [1:3] 221293 80396 864701
##   .. ..$ : int [1:3] 391888 381838 153141
##   .. ..$ : int 679141
##   ..$ adaptive         :List of 4
##   .. ..$ min     : num 5
##   .. ..$ alpha   : num 0.05
##   .. ..$ method  : chr "gls"
##   .. ..$ complete: logi TRUE
##   ..$ trim             : logi FALSE
##   ..$ allowParallel    : logi TRUE
##  $ finalModel  :List of 23
##   ..$ call           : language randomForest(x = x, y = y, mtry = param$mtry)
##   ..$ type           : chr "classification"
##   ..$ predicted      : Factor w/ 2 levels "neg","pos": 2 1 2 1 2 1 1 2 2 1 ...
##   .. ..- attr(*, "names")= chr [1:768] "X1" "X2" "X3" "X4" ...
##   ..$ err.rate       : num [1:500, 1:3] 0.284 0.32 0.347 0.302 0.307 ...
##   .. ..- attr(*, "dimnames")=List of 2
##   ..$ confusion      : num [1:2, 1:3] 427 104 73 164 0.146 ...
##   .. ..- attr(*, "dimnames")=List of 2
##   ..$ votes          : 'matrix' num [1:768, 1:2] 0.331 0.868 0.471 0.989 0.345 ...
##   .. ..- attr(*, "dimnames")=List of 2
##   ..$ oob.times      : num [1:768] 178 182 172 181 197 185 172 191 196 170 ...
##   ..$ classes        : chr [1:2] "neg" "pos"
##   ..$ importance     : num [1:8, 1] 29.2 91.3 31.3 23.6 24.8 ...
##   .. ..- attr(*, "dimnames")=List of 2
##   ..$ importanceSD   : NULL
##   ..$ localImportance: NULL
##   ..$ proximity      : NULL
##   ..$ ntree          : num 500
##   ..$ mtry           : num 2
##   ..$ forest         :List of 14
##   .. ..$ ndbigtree : int [1:500] 273 265 247 249 261 277 269 281 261 255 ...
##   .. ..$ nodestatus: int [1:311, 1:500] 1 1 1 1 1 1 1 1 1 1 ...
##   .. ..$ bestvar   : int [1:311, 1:500] 8 2 4 4 3 8 1 1 4 4 ...
##   .. ..$ treemap   : int [1:311, 1:2, 1:500] 2 4 6 8 10 12 14 16 18 20 ...
##   .. ..$ nodepred  : int [1:311, 1:500] 0 0 0 0 0 0 0 0 0 0 ...
##   .. ..$ xbestsplit: num [1:311, 1:500] -0.40313 1.05107 -0.00229 -1.03662 1.02783 ...
##   .. ..$ pid       : num [1:2] 1 1
##   .. ..$ cutoff    : num [1:2] 0.5 0.5
##   .. ..$ ncat      : Named num [1:8] 1 1 1 1 1 1 1 1
##   .. .. ..- attr(*, "names")= chr [1:8] "pregnant" "glucose" "pressure" "triceps" ...
##   .. ..$ maxcat    : num 1
##   .. ..$ nrnodes   : int 311
##   .. ..$ ntree     : num 500
##   .. ..$ nclass    : int 2
##   .. ..$ xlevels   :List of 8
##   ..$ y              : Factor w/ 2 levels "neg","pos": 2 1 2 1 2 1 2 1 2 2 ...
##   .. ..- attr(*, "names")= chr [1:768] "1" "2" "3" "4" ...
##   ..$ test           : NULL
##   ..$ inbag          : NULL
##   ..$ xNames         : chr [1:8] "pregnant" "glucose" "pressure" "triceps" ...
##   ..$ problemType    : chr "Classification"
##   ..$ tuneValue      :'data.frame':  1 obs. of  1 variable:
##   .. ..$ mtry: num 2
##   ..$ obsLevels      : chr [1:2] "neg" "pos"
##   .. ..- attr(*, "ordered")= logi FALSE
##   ..$ param          : list()
##   ..- attr(*, "class")= chr "randomForest"
##  $ preProcess  :List of 22
##   ..$ dim              : int [1:2] 768 8
##   ..$ bc               : NULL
##   ..$ yj               : NULL
##   ..$ et               : NULL
##   ..$ invHyperbolicSine: NULL
##   ..$ mean             : Named num [1:8] 3.85 120.89 69.11 20.54 79.8 ...
##   .. ..- attr(*, "names")= chr [1:8] "pregnant" "glucose" "pressure" "triceps" ...
##   ..$ std              : Named num [1:8] 3.37 31.97 19.36 15.95 115.24 ...
##   .. ..- attr(*, "names")= chr [1:8] "pregnant" "glucose" "pressure" "triceps" ...
##   ..$ ranges           : NULL
##   ..$ rotation         : NULL
##   ..$ method           :List of 3
##   .. ..$ center: chr [1:8] "pregnant" "glucose" "pressure" "triceps" ...
##   .. ..$ scale : chr [1:8] "pregnant" "glucose" "pressure" "triceps" ...
##   .. ..$ ignore: chr(0) 
##   ..$ thresh           : num 0.95
##   ..$ pcaComp          : NULL
##   ..$ numComp          : NULL
##   ..$ ica              : NULL
##   ..$ wildcards        :List of 2
##   .. ..$ PCA: chr(0) 
##   .. ..$ ICA: chr(0) 
##   ..$ k                : num 5
##   ..$ knnSummary       :function (x, ...)  
##   ..$ bagImp           : NULL
##   ..$ median           : NULL
##   ..$ data             : NULL
##   ..$ rangeBounds      : num [1:2] 0 1
##   ..$ call             : chr "scrubed"
##   ..- attr(*, "class")= chr "preProcess"
##  $ trainingData:'data.frame':    768 obs. of  9 variables:
##   ..$ .outcome: Factor w/ 2 levels "neg","pos": 2 1 2 1 2 1 2 1 2 2 ...
##   ..$ pregnant: num [1:768] 6 1 8 1 0 5 3 10 2 8 ...
##   ..$ glucose : num [1:768] 148 85 183 89 137 116 78 115 197 125 ...
##   ..$ pressure: num [1:768] 72 66 64 66 40 74 50 0 70 96 ...
##   ..$ triceps : num [1:768] 35 29 0 23 35 0 32 0 45 0 ...
##   ..$ insulin : num [1:768] 0 0 0 94 168 0 88 0 543 0 ...
##   ..$ mass    : num [1:768] 33.6 26.6 23.3 28.1 43.1 25.6 31 35.3 30.5 0 ...
##   ..$ pedigree: num [1:768] 0.627 0.351 0.672 0.167 2.288 ...
##   ..$ age     : num [1:768] 50 31 32 21 33 30 26 29 53 54 ...
##  $ ptype       :'data.frame':    0 obs. of  8 variables:
##   ..$ pregnant: num(0) 
##   ..$ glucose : num(0) 
##   ..$ pressure: num(0) 
##   ..$ triceps : num(0) 
##   ..$ insulin : num(0) 
##   ..$ mass    : num(0) 
##   ..$ pedigree: num(0) 
##   ..$ age     : num(0) 
##  $ resample    :'data.frame':    5 obs. of  3 variables:
##   ..$ Accuracy: num [1:5] 0.797 0.779 0.753 0.706 0.812
##   ..$ Kappa   : num [1:5] 0.551 0.507 0.419 0.359 0.57
##   ..$ Resample: chr [1:5] "Fold1.Rep1" "Fold2.Rep1" "Fold5.Rep1" "Fold4.Rep1" ...
##  $ resampledCM :'data.frame':    15 obs. of  6 variables:
##   ..$ cell1   : num [1:15] 85 83 82 85 81 81 90 90 88 76 ...
##   ..$ cell2   : num [1:15] 15 17 18 15 19 19 10 10 12 24 ...
##   ..$ cell3   : num [1:15] 16 16 18 19 19 19 19 18 19 21 ...
##   ..$ cell4   : num [1:15] 37 37 35 35 35 35 35 36 35 32 ...
##   ..$ mtry    : num [1:15] 2 5 8 2 5 8 2 5 8 2 ...
##   ..$ Resample: chr [1:15] "Fold1.Rep1" "Fold1.Rep1" "Fold1.Rep1" "Fold2.Rep1" ...
##  $ perfNames   : chr [1:2] "Accuracy" "Kappa"
##  $ maximize    : logi TRUE
##  $ yLimits     : NULL
##  $ times       :List of 3
##   ..$ everything: 'proc_time' Named num [1:5] 2.11 0.07 4.83 NA NA
##   .. ..- attr(*, "names")= chr [1:5] "user.self" "sys.self" "elapsed" "user.child" ...
##   ..$ final     : 'proc_time' Named num [1:5] 0.2 0 0.42 NA NA
##   .. ..- attr(*, "names")= chr [1:5] "user.self" "sys.self" "elapsed" "user.child" ...
##   ..$ prediction: logi [1:3] NA NA NA
##  $ levels      : chr [1:2] "neg" "pos"
##   ..- attr(*, "ordered")= logi FALSE
##  $ terms       :Classes 'terms', 'formula'  language diabetes ~ pregnant + glucose + pressure + triceps + insulin + mass + pedigree +      age
##   .. ..- attr(*, "variables")= language list(diabetes, pregnant, glucose, pressure, triceps, insulin, mass, pedigree,      age)
##   .. ..- attr(*, "factors")= int [1:9, 1:8] 0 1 0 0 0 0 0 0 0 0 ...
##   .. .. ..- attr(*, "dimnames")=List of 2
##   .. ..- attr(*, "term.labels")= chr [1:8] "pregnant" "glucose" "pressure" "triceps" ...
##   .. ..- attr(*, "order")= int [1:8] 1 1 1 1 1 1 1 1
##   .. ..- attr(*, "intercept")= int 1
##   .. ..- attr(*, "response")= int 1
##   .. ..- attr(*, ".Environment")=<environment: R_GlobalEnv> 
##   .. ..- attr(*, "predvars")= language list(diabetes, pregnant, glucose, pressure, triceps, insulin, mass, pedigree,      age)
##   .. ..- attr(*, "dataClasses")= Named chr [1:9] "factor" "numeric" "numeric" "numeric" ...
##   .. .. ..- attr(*, "names")= chr [1:9] "diabetes" "pregnant" "glucose" "pressure" ...
##  $ coefnames   : chr [1:8] "pregnant" "glucose" "pressure" "triceps" ...
##  $ xlevels     : Named list()
##  - attr(*, "class")= chr [1:2] "train" "train.formula"
model
## Random Forest 
## 
## 768 samples
##   8 predictor
##   2 classes: 'neg', 'pos' 
## 
## Pre-processing: centered (8), scaled (8) 
## Resampling: Cross-Validated (5 fold, repeated 1 times) 
## Summary of sample sizes: 615, 614, 614, 615, 614 
## Resampling results across tuning parameters:
## 
##   mtry  Accuracy   Kappa    
##   2     0.7694848  0.4809709
##   5     0.7577710  0.4552707
##   8     0.7538664  0.4471454
## 
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was mtry = 2.
model1<-train(diabetes~.,data=PimaIndiansDiabetes,method="knn",preProcess=c("center","scale"),trControl=control)
glimpse(model1)
## List of 24
##  $ method      : chr "knn"
##  $ modelInfo   :List of 13
##   ..$ label     : chr "k-Nearest Neighbors"
##   ..$ library   : NULL
##   ..$ loop      : NULL
##   ..$ type      : chr [1:2] "Classification" "Regression"
##   ..$ parameters:'data.frame':   1 obs. of  3 variables:
##   .. ..$ parameter: chr "k"
##   .. ..$ class    : chr "numeric"
##   .. ..$ label    : chr "#Neighbors"
##   ..$ grid      :function (x, y, len = NULL, search = "grid")  
##   ..$ fit       :function (x, y, wts, param, lev, last, classProbs, ...)  
##   ..$ predict   :function (modelFit, newdata, submodels = NULL)  
##   ..$ predictors:function (x, ...)  
##   ..$ tags      : chr "Prototype Models"
##   ..$ prob      :function (modelFit, newdata, submodels = NULL)  
##   ..$ levels    :function (x)  
##   ..$ sort      :function (x)  
##  $ modelType   : chr "Classification"
##  $ results     :'data.frame':    3 obs. of  5 variables:
##   ..$ k         : int [1:3] 5 7 9
##   ..$ Accuracy  : num [1:3] 0.729 0.745 0.742
##   ..$ Kappa     : num [1:3] 0.382 0.421 0.41
##   ..$ AccuracySD: num [1:3] 0.0197 0.0221 0.0301
##   ..$ KappaSD   : num [1:3] 0.051 0.0643 0.0806
##  $ pred        : NULL
##  $ bestTune    :'data.frame':    1 obs. of  1 variable:
##   ..$ k: int 7
##  $ call        : language train.formula(form = diabetes ~ ., data = PimaIndiansDiabetes, method = "knn",      preProcess = c("center", "sca| __truncated__
##  $ dots        : list()
##  $ metric      : chr "Accuracy"
##  $ control     :List of 27
##   ..$ method           : chr "repeatedcv"
##   ..$ number           : num 5
##   ..$ repeats          : num 1
##   ..$ search           : chr "grid"
##   ..$ p                : num 0.75
##   ..$ initialWindow    : NULL
##   ..$ horizon          : num 1
##   ..$ fixedWindow      : logi TRUE
##   ..$ skip             : num 0
##   ..$ verboseIter      : logi FALSE
##   ..$ returnData       : logi TRUE
##   ..$ returnResamp     : chr "final"
##   ..$ savePredictions  : chr "none"
##   ..$ classProbs       : logi FALSE
##   ..$ summaryFunction  :function (data, lev = NULL, model = NULL)  
##   ..$ selectionFunction: chr "best"
##   ..$ preProcOptions   :List of 6
##   .. ..$ thresh   : num 0.95
##   .. ..$ ICAcomp  : num 3
##   .. ..$ k        : num 5
##   .. ..$ freqCut  : num 19
##   .. ..$ uniqueCut: num 10
##   .. ..$ cutoff   : num 0.9
##   ..$ sampling         : NULL
##   ..$ index            :List of 5
##   .. ..$ Fold1.Rep1: int [1:615] 1 2 3 4 5 6 7 8 9 10 ...
##   .. ..$ Fold2.Rep1: int [1:615] 1 4 5 6 8 9 10 11 14 15 ...
##   .. ..$ Fold3.Rep1: int [1:614] 1 2 3 4 5 7 8 10 11 12 ...
##   .. ..$ Fold4.Rep1: int [1:614] 1 2 3 6 7 9 10 12 13 14 ...
##   .. ..$ Fold5.Rep1: int [1:614] 2 3 4 5 6 7 8 9 11 12 ...
##   ..$ indexOut         :List of 5
##   .. ..$ Resample1: int [1:153] 19 20 32 37 40 41 49 60 62 63 ...
##   .. ..$ Resample2: int [1:153] 2 3 7 12 13 18 22 29 31 33 ...
##   .. ..$ Resample3: int [1:154] 6 9 14 15 16 21 25 28 42 57 ...
##   .. ..$ Resample4: int [1:154] 4 5 8 11 17 23 30 35 43 44 ...
##   .. ..$ Resample5: int [1:154] 1 10 24 26 27 34 38 39 51 54 ...
##   ..$ indexFinal       : NULL
##   ..$ timingSamps      : num 0
##   ..$ predictionBounds : logi [1:2] FALSE FALSE
##   ..$ seeds            :List of 6
##   .. ..$ : int [1:3] 333601 781995 566217
##   .. ..$ : int [1:3] 106005 369567 141839
##   .. ..$ : int [1:3] 614935 802282 556785
##   .. ..$ : int [1:3] 276991 786510 13406
##   .. ..$ : int [1:3] 647761 71443 928755
##   .. ..$ : int 71058
##   ..$ adaptive         :List of 4
##   .. ..$ min     : num 5
##   .. ..$ alpha   : num 0.05
##   .. ..$ method  : chr "gls"
##   .. ..$ complete: logi TRUE
##   ..$ trim             : logi FALSE
##   ..$ allowParallel    : logi TRUE
##  $ finalModel  :List of 8
##   ..$ learn      :List of 2
##   .. ..$ y: Factor w/ 2 levels "neg","pos": 2 1 2 1 2 1 2 1 2 2 ...
##   .. .. ..- attr(*, "names")= chr [1:768] "1" "2" "3" "4" ...
##   .. ..$ X: num [1:768, 1:8] 0.64 -0.844 1.233 -0.844 -1.141 ...
##   .. .. ..- attr(*, "dimnames")=List of 2
##   ..$ k          : int 7
##   ..$ theDots    : list()
##   ..$ xNames     : chr [1:8] "pregnant" "glucose" "pressure" "triceps" ...
##   ..$ problemType: chr "Classification"
##   ..$ tuneValue  :'data.frame':  1 obs. of  1 variable:
##   .. ..$ k: int 7
##   ..$ obsLevels  : chr [1:2] "neg" "pos"
##   .. ..- attr(*, "ordered")= logi FALSE
##   ..$ param      : list()
##   ..- attr(*, "class")= chr "knn3"
##  $ preProcess  :List of 22
##   ..$ dim              : int [1:2] 768 8
##   ..$ bc               : NULL
##   ..$ yj               : NULL
##   ..$ et               : NULL
##   ..$ invHyperbolicSine: NULL
##   ..$ mean             : Named num [1:8] 3.85 120.89 69.11 20.54 79.8 ...
##   .. ..- attr(*, "names")= chr [1:8] "pregnant" "glucose" "pressure" "triceps" ...
##   ..$ std              : Named num [1:8] 3.37 31.97 19.36 15.95 115.24 ...
##   .. ..- attr(*, "names")= chr [1:8] "pregnant" "glucose" "pressure" "triceps" ...
##   ..$ ranges           : NULL
##   ..$ rotation         : NULL
##   ..$ method           :List of 3
##   .. ..$ center: chr [1:8] "pregnant" "glucose" "pressure" "triceps" ...
##   .. ..$ scale : chr [1:8] "pregnant" "glucose" "pressure" "triceps" ...
##   .. ..$ ignore: chr(0) 
##   ..$ thresh           : num 0.95
##   ..$ pcaComp          : NULL
##   ..$ numComp          : NULL
##   ..$ ica              : NULL
##   ..$ wildcards        :List of 2
##   .. ..$ PCA: chr(0) 
##   .. ..$ ICA: chr(0) 
##   ..$ k                : num 5
##   ..$ knnSummary       :function (x, ...)  
##   ..$ bagImp           : NULL
##   ..$ median           : NULL
##   ..$ data             : NULL
##   ..$ rangeBounds      : num [1:2] 0 1
##   ..$ call             : chr "scrubed"
##   ..- attr(*, "class")= chr "preProcess"
##  $ trainingData:'data.frame':    768 obs. of  9 variables:
##   ..$ .outcome: Factor w/ 2 levels "neg","pos": 2 1 2 1 2 1 2 1 2 2 ...
##   ..$ pregnant: num [1:768] 6 1 8 1 0 5 3 10 2 8 ...
##   ..$ glucose : num [1:768] 148 85 183 89 137 116 78 115 197 125 ...
##   ..$ pressure: num [1:768] 72 66 64 66 40 74 50 0 70 96 ...
##   ..$ triceps : num [1:768] 35 29 0 23 35 0 32 0 45 0 ...
##   ..$ insulin : num [1:768] 0 0 0 94 168 0 88 0 543 0 ...
##   ..$ mass    : num [1:768] 33.6 26.6 23.3 28.1 43.1 25.6 31 35.3 30.5 0 ...
##   ..$ pedigree: num [1:768] 0.627 0.351 0.672 0.167 2.288 ...
##   ..$ age     : num [1:768] 50 31 32 21 33 30 26 29 53 54 ...
##  $ ptype       :'data.frame':    0 obs. of  8 variables:
##   ..$ pregnant: num(0) 
##   ..$ glucose : num(0) 
##   ..$ pressure: num(0) 
##   ..$ triceps : num(0) 
##   ..$ insulin : num(0) 
##   ..$ mass    : num(0) 
##   ..$ pedigree: num(0) 
##   ..$ age     : num(0) 
##  $ resample    :'data.frame':    5 obs. of  3 variables:
##   ..$ Accuracy: num [1:5] 0.771 0.734 0.725 0.727 0.766
##   ..$ Kappa   : num [1:5] 0.474 0.413 0.383 0.339 0.495
##   ..$ Resample: chr [1:5] "Fold1.Rep1" "Fold3.Rep1" "Fold2.Rep1" "Fold5.Rep1" ...
##  $ resampledCM :'data.frame':    15 obs. of  6 variables:
##   ..$ cell1   : num [1:15] 82 87 90 81 81 81 83 80 83 81 ...
##   ..$ cell2   : num [1:15] 18 13 10 19 19 19 17 20 17 19 ...
##   ..$ cell3   : num [1:15] 26 22 23 26 23 23 24 21 24 19 ...
##   ..$ cell4   : num [1:15] 27 31 30 27 30 30 30 33 30 35 ...
##   ..$ k       : int [1:15] 5 7 9 5 7 9 5 7 9 5 ...
##   ..$ Resample: chr [1:15] "Fold1.Rep1" "Fold1.Rep1" "Fold1.Rep1" "Fold2.Rep1" ...
##  $ perfNames   : chr [1:2] "Accuracy" "Kappa"
##  $ maximize    : logi TRUE
##  $ yLimits     : NULL
##  $ times       :List of 3
##   ..$ everything: 'proc_time' Named num [1:5] 0.05 0 0.25 NA NA
##   .. ..- attr(*, "names")= chr [1:5] "user.self" "sys.self" "elapsed" "user.child" ...
##   ..$ final     : 'proc_time' Named num [1:5] 0 0 0 NA NA
##   .. ..- attr(*, "names")= chr [1:5] "user.self" "sys.self" "elapsed" "user.child" ...
##   ..$ prediction: logi [1:3] NA NA NA
##  $ levels      : chr [1:2] "neg" "pos"
##   ..- attr(*, "ordered")= logi FALSE
##  $ terms       :Classes 'terms', 'formula'  language diabetes ~ pregnant + glucose + pressure + triceps + insulin + mass + pedigree +      age
##   .. ..- attr(*, "variables")= language list(diabetes, pregnant, glucose, pressure, triceps, insulin, mass, pedigree,      age)
##   .. ..- attr(*, "factors")= int [1:9, 1:8] 0 1 0 0 0 0 0 0 0 0 ...
##   .. .. ..- attr(*, "dimnames")=List of 2
##   .. ..- attr(*, "term.labels")= chr [1:8] "pregnant" "glucose" "pressure" "triceps" ...
##   .. ..- attr(*, "order")= int [1:8] 1 1 1 1 1 1 1 1
##   .. ..- attr(*, "intercept")= int 1
##   .. ..- attr(*, "response")= int 1
##   .. ..- attr(*, ".Environment")=<environment: R_GlobalEnv> 
##   .. ..- attr(*, "predvars")= language list(diabetes, pregnant, glucose, pressure, triceps, insulin, mass, pedigree,      age)
##   .. ..- attr(*, "dataClasses")= Named chr [1:9] "factor" "numeric" "numeric" "numeric" ...
##   .. .. ..- attr(*, "names")= chr [1:9] "diabetes" "pregnant" "glucose" "pressure" ...
##  $ coefnames   : chr [1:8] "pregnant" "glucose" "pressure" "triceps" ...
##  $ xlevels     : Named list()
##  - attr(*, "class")= chr [1:2] "train" "train.formula"
model1
## k-Nearest Neighbors 
## 
## 768 samples
##   8 predictor
##   2 classes: 'neg', 'pos' 
## 
## Pre-processing: centered (8), scaled (8) 
## Resampling: Cross-Validated (5 fold, repeated 1 times) 
## Summary of sample sizes: 615, 615, 614, 614, 614 
## Resampling results across tuning parameters:
## 
##   k  Accuracy   Kappa    
##   5  0.7291147  0.3818076
##   7  0.7448010  0.4207935
##   9  0.7422205  0.4098283
## 
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was k = 7.
model
## Random Forest 
## 
## 768 samples
##   8 predictor
##   2 classes: 'neg', 'pos' 
## 
## Pre-processing: centered (8), scaled (8) 
## Resampling: Cross-Validated (5 fold, repeated 1 times) 
## Summary of sample sizes: 615, 614, 614, 615, 614 
## Resampling results across tuning parameters:
## 
##   mtry  Accuracy   Kappa    
##   2     0.7694848  0.4809709
##   5     0.7577710  0.4552707
##   8     0.7538664  0.4471454
## 
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was mtry = 2.
importance<-varImp(model,scale=FALSE)
print(importance)
## rf variable importance
## 
##          Overall
## glucose    91.28
## mass       57.41
## age        46.74
## pedigree   42.62
## pressure   31.33
## pregnant   29.25
## insulin    24.83
## triceps    23.59
plot(importance)

library(mlbench)
library(caret)
data(PimaIndiansDiabetes)
control <- rfeControl(functions=rfFuncs, method="cv", number=10)

results <- rfe(PimaIndiansDiabetes[,1:8], PimaIndiansDiabetes[,9], sizes=c(1:8), rfeControl=control)

print(results)               
## 
## Recursive feature selection
## 
## Outer resampling method: Cross-Validated (10 fold) 
## 
## Resampling performance over subset size:
## 
##  Variables Accuracy  Kappa AccuracySD KappaSD Selected
##          1   0.7124 0.3111    0.05186 0.13890         
##          2   0.7332 0.3924    0.04711 0.10639         
##          3   0.7476 0.4293    0.04875 0.11184         
##          4   0.7592 0.4611    0.04751 0.10131         
##          5   0.7605 0.4554    0.04122 0.09108         
##          6   0.7644 0.4656    0.04727 0.10522         
##          7   0.7566 0.4473    0.03705 0.08515         
##          8   0.7735 0.4828    0.03773 0.09149        *
## 
## The top 5 variables (out of 8):
##    glucose, mass, age, pregnant, pedigree
predictors(results)
## [1] "glucose"  "mass"     "age"      "pregnant" "pedigree" "insulin"  "triceps" 
## [8] "pressure"
data(Sonar)
set.seed(998)
inTraining<- createDataPartition(y = Sonar$Class,p = .75, list = FALSE)
training <- Sonar[ inTraining,]
testing <- Sonar[-inTraining,]
rffit <- train(Class ~ ., data = training,method = "rf",preProc = c("center", "scale"))
rffit
## Random Forest 
## 
## 157 samples
##  60 predictor
##   2 classes: 'M', 'R' 
## 
## Pre-processing: centered (60), scaled (60) 
## Resampling: Bootstrapped (25 reps) 
## Summary of sample sizes: 157, 157, 157, 157, 157, 157, ... 
## Resampling results across tuning parameters:
## 
##   mtry  Accuracy   Kappa    
##    2    0.7946302  0.5834287
##   31    0.7951860  0.5836850
##   60    0.7880609  0.5689185
## 
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was mtry = 31.
fitControl <- trainControl(method = "repeatedcv",number = 5, classProbs = TRUE,summaryFunction = twoClassSummary)
set.seed(825)
rmfit1 <- train(Class~.,data=training,method="rf",trControl=fitControl,verbose=FALSE,metric="ROC")
rmfit1
## Random Forest 
## 
## 157 samples
##  60 predictor
##   2 classes: 'M', 'R' 
## 
## No pre-processing
## Resampling: Cross-Validated (5 fold, repeated 1 times) 
## Summary of sample sizes: 125, 125, 125, 127, 126 
## Resampling results across tuning parameters:
## 
##   mtry  ROC        Sens       Spec     
##    2    0.9317665  0.9176471  0.7533333
##   31    0.9252381  0.8816176  0.7247619
##   60    0.9146569  0.8580882  0.7514286
## 
## ROC was used to select the optimal model using the largest value.
## The final value used for the model was mtry = 2.
set.seed(825)
customGrid <- expand.grid(mtry = 1:10)
rffit2 <- train(Class ~ ., data = training, method = "rf", trControl = fitControl,tuneGrid = customGrid, metric = "ROC")
rffit2
## Random Forest 
## 
## 157 samples
##  60 predictor
##   2 classes: 'M', 'R' 
## 
## No pre-processing
## Resampling: Cross-Validated (5 fold, repeated 1 times) 
## Summary of sample sizes: 125, 125, 125, 127, 126 
## Resampling results across tuning parameters:
## 
##   mtry  ROC        Sens       Spec     
##    1    0.9287640  0.9411765  0.6847619
##    2    0.9371078  0.9058824  0.7533333
##    3    0.9399545  0.9058824  0.7380952
##    4    0.9392787  0.8823529  0.7657143
##    5    0.9365546  0.8941176  0.7523810
##    6    0.9297094  0.8941176  0.7523810
##    7    0.9347584  0.8941176  0.7238095
##    8    0.9331863  0.8816176  0.7800000
##    9    0.9364741  0.8816176  0.7390476
##   10    0.9285399  0.8823529  0.7390476
## 
## ROC was used to select the optimal model using the largest value.
## The final value used for the model was mtry = 3.
set.seed(825)
fitControl <- trainControl(method = "repeatedcv", number = 5,classProbs = TRUE,summaryFunction = twoClassSummary, search = "random")
rffit3 <- train(Class ~ ., data = training, method = "rf", metric = "ROC", trControl = fitControl)
rffit3
## Random Forest 
## 
## 157 samples
##  60 predictor
##   2 classes: 'M', 'R' 
## 
## No pre-processing
## Resampling: Cross-Validated (5 fold, repeated 1 times) 
## Summary of sample sizes: 125, 125, 125, 127, 126 
## Resampling results across tuning parameters:
## 
##   mtry  ROC        Sens       Spec     
##   26    0.9208824  0.8698529  0.7800000
##   42    0.9162290  0.8816176  0.7380952
##   56    0.9154237  0.8698529  0.7523810
## 
## ROC was used to select the optimal model using the largest value.
## The final value used for the model was mtry = 26.
set.seed(825)
fitControl <- trainControl(method = "repeatedcv", number = 5,classProbs = TRUE,summaryFunction = twoClassSummary)
rffit4 <- train(Class ~ ., data = training, method = "rf", trControl = fitControl, tuneLength = 20)
## Warning in train.default(x, y, weights = w, ...): The metric "Accuracy" was not
## in the result set. ROC will be used instead.
rffit4
## Random Forest 
## 
## 157 samples
##  60 predictor
##   2 classes: 'M', 'R' 
## 
## No pre-processing
## Resampling: Cross-Validated (5 fold, repeated 1 times) 
## Summary of sample sizes: 125, 125, 125, 127, 126 
## Resampling results across tuning parameters:
## 
##   mtry  ROC        Sens       Spec     
##    2    0.9133386  0.8941176  0.6971429
##    5    0.9254359  0.8823529  0.7514286
##    8    0.9377556  0.8823529  0.7800000
##   11    0.9293085  0.8823529  0.7380952
##   14    0.9175280  0.8816176  0.7523810
##   17    0.9265581  0.8816176  0.7247619
##   20    0.9206478  0.8816176  0.7657143
##   23    0.9246569  0.8816176  0.7390476
##   26    0.9183613  0.8816176  0.7523810
##   29    0.9225000  0.8816176  0.7666667
##   32    0.9210399  0.8816176  0.7523810
##   35    0.9198687  0.8698529  0.7247619
##   38    0.9218803  0.8816176  0.7247619
##   41    0.9198109  0.8698529  0.7533333
##   44    0.9176313  0.8580882  0.7666667
##   47    0.9171849  0.8580882  0.7533333
##   50    0.9200123  0.8698529  0.7247619
##   53    0.9167787  0.8698529  0.7666667
##   56    0.9160644  0.8698529  0.7390476
##   60    0.9180795  0.8816176  0.7390476
## 
## ROC was used to select the optimal model using the largest value.
## The final value used for the model was mtry = 8.
predict(rmfit1,newdata=head(testing))
## [1] R M R M M M
## Levels: M R
predict(rmfit1,newdata=head(testing),type='prob')
##        M     R
## 4  0.446 0.554
## 8  0.630 0.370
## 11 0.088 0.912
## 14 0.506 0.494
## 15 0.546 0.454
## 17 0.620 0.380
library(dplyr)
predict(rmfit1,newdata=testing) %>% confusionMatrix(testing$Class)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  M  R
##          M 24  5
##          R  3 19
##                                           
##                Accuracy : 0.8431          
##                  95% CI : (0.7141, 0.9298)
##     No Information Rate : 0.5294          
##     P-Value [Acc > NIR] : 2.534e-06       
##                                           
##                   Kappa : 0.6837          
##                                           
##  Mcnemar's Test P-Value : 0.7237          
##                                           
##             Sensitivity : 0.8889          
##             Specificity : 0.7917          
##          Pos Pred Value : 0.8276          
##          Neg Pred Value : 0.8636          
##              Prevalence : 0.5294          
##          Detection Rate : 0.4706          
##    Detection Prevalence : 0.5686          
##       Balanced Accuracy : 0.8403          
##                                           
##        'Positive' Class : M               
## 
#install.packages("caTools")
library(caTools)
setwd("C:/data/source data")
df<-read.csv("diagnosis.csv")
glimpse(df) 
## Rows: 569
## Columns: 32
## $ id                      <int> 842302, 842517, 84300903, 84348301, 84358402, …
## $ diagnosis               <chr> "M", "M", "M", "M", "M", "M", "M", "M", "M", "…
## $ radius_mean             <dbl> 17.990, 20.570, 19.690, 11.420, 20.290, 12.450…
## $ texture_mean            <dbl> 10.38, 17.77, 21.25, 20.38, 14.34, 15.70, 19.9…
## $ perimeter_mean          <dbl> 122.80, 132.90, 130.00, 77.58, 135.10, 82.57, …
## $ area_mean               <dbl> 1001.0, 1326.0, 1203.0, 386.1, 1297.0, 477.1, …
## $ smoothness_mean         <dbl> 0.11840, 0.08474, 0.10960, 0.14250, 0.10030, 0…
## $ compactness_mean        <dbl> 0.27760, 0.07864, 0.15990, 0.28390, 0.13280, 0…
## $ concavity_mean          <dbl> 0.30010, 0.08690, 0.19740, 0.24140, 0.19800, 0…
## $ concave.points_mean     <dbl> 0.14710, 0.07017, 0.12790, 0.10520, 0.10430, 0…
## $ symmetry_mean           <dbl> 0.2419, 0.1812, 0.2069, 0.2597, 0.1809, 0.2087…
## $ fractal_dimension_mean  <dbl> 0.07871, 0.05667, 0.05999, 0.09744, 0.05883, 0…
## $ radius_se               <dbl> 1.0950, 0.5435, 0.7456, 0.4956, 0.7572, 0.3345…
## $ texture_se              <dbl> 0.9053, 0.7339, 0.7869, 1.1560, 0.7813, 0.8902…
## $ perimeter_se            <dbl> 8.589, 3.398, 4.585, 3.445, 5.438, 2.217, 3.18…
## $ area_se                 <dbl> 153.40, 74.08, 94.03, 27.23, 94.44, 27.19, 53.…
## $ smoothness_se           <dbl> 0.006399, 0.005225, 0.006150, 0.009110, 0.0114…
## $ compactness_se          <dbl> 0.049040, 0.013080, 0.040060, 0.074580, 0.0246…
## $ concavity_se            <dbl> 0.05373, 0.01860, 0.03832, 0.05661, 0.05688, 0…
## $ concave.points_se       <dbl> 0.015870, 0.013400, 0.020580, 0.018670, 0.0188…
## $ symmetry_se             <dbl> 0.03003, 0.01389, 0.02250, 0.05963, 0.01756, 0…
## $ fractal_dimension_se    <dbl> 0.006193, 0.003532, 0.004571, 0.009208, 0.0051…
## $ radius_worst            <dbl> 25.38, 24.99, 23.57, 14.91, 22.54, 15.47, 22.8…
## $ texture_worst           <dbl> 17.33, 23.41, 25.53, 26.50, 16.67, 23.75, 27.6…
## $ perimeter_worst         <dbl> 184.60, 158.80, 152.50, 98.87, 152.20, 103.40,…
## $ area_worst              <dbl> 2019.0, 1956.0, 1709.0, 567.7, 1575.0, 741.6, …
## $ smoothness_worst        <dbl> 0.1622, 0.1238, 0.1444, 0.2098, 0.1374, 0.1791…
## $ compactness_worst       <dbl> 0.6656, 0.1866, 0.4245, 0.8663, 0.2050, 0.5249…
## $ concavity_worst         <dbl> 0.71190, 0.24160, 0.45040, 0.68690, 0.40000, 0…
## $ concave.points_worst    <dbl> 0.26540, 0.18600, 0.24300, 0.25750, 0.16250, 0…
## $ symmetry_worst          <dbl> 0.4601, 0.2750, 0.3613, 0.6638, 0.2364, 0.3985…
## $ fractal_dimension_worst <dbl> 0.11890, 0.08902, 0.08758, 0.17300, 0.07678, 0…
colSums(is.na(df))
##                      id               diagnosis             radius_mean 
##                       0                       0                       0 
##            texture_mean          perimeter_mean               area_mean 
##                       0                       0                       0 
##         smoothness_mean        compactness_mean          concavity_mean 
##                       0                       0                       0 
##     concave.points_mean           symmetry_mean  fractal_dimension_mean 
##                       0                       0                       0 
##               radius_se              texture_se            perimeter_se 
##                       0                       0                       0 
##                 area_se           smoothness_se          compactness_se 
##                       0                       0                       0 
##            concavity_se       concave.points_se             symmetry_se 
##                       0                       0                       0 
##    fractal_dimension_se            radius_worst           texture_worst 
##                       0                       0                       0 
##         perimeter_worst              area_worst        smoothness_worst 
##                       0                       0                       0 
##       compactness_worst         concavity_worst    concave.points_worst 
##                       0                       0                       0 
##          symmetry_worst fractal_dimension_worst 
##                       0                       0
df <- df %>% select(-id)
df$diagnosis <- as.factor(df$diagnosis)
prop.table(table(df$diagnosis))
## 
##         B         M 
## 0.6274165 0.3725835
any(is.na(df))
## [1] FALSE
set.seed(3)
inTraining<- createDataPartition(y = df$diagnosis,p = .75, list = FALSE) 
training <- df[ inTraining,]
testing <- df[-inTraining,]

my_trainControl<- trainControl(method = "repeatedcv",number = 5,classProbs = TRUE,summaryFunction = twoClassSummary)

glmnetfit <- train(diagnosis ~ ., data = training, method = "glmnet", trControl = fitControl, verbose = FALSE, metric = "ROC")
glmnetfit
## glmnet 
## 
## 427 samples
##  30 predictor
##   2 classes: 'B', 'M' 
## 
## No pre-processing
## Resampling: Cross-Validated (5 fold, repeated 1 times) 
## Summary of sample sizes: 342, 341, 343, 341, 341 
## Resampling results across tuning parameters:
## 
##   alpha  lambda        ROC        Sens       Spec     
##   0.10   0.0007738036  0.9931304  0.9850454  0.9560484
##   0.10   0.0077380355  0.9941928  0.9962963  0.9372984
##   0.10   0.0773803551  0.9937380  0.9962963  0.9054435
##   0.55   0.0007738036  0.9930087  0.9850454  0.9497984
##   0.55   0.0077380355  0.9943107  0.9962963  0.9497984
##   0.55   0.0773803551  0.9931533  0.9962963  0.8741935
##   1.00   0.0007738036  0.9921904  0.9776380  0.9435484
##   1.00   0.0077380355  0.9941966  0.9962963  0.9370968
##   1.00   0.0773803551  0.9907960  0.9925926  0.8614919
## 
## ROC was used to select the optimal model using the largest value.
## The final values used for the model were alpha = 0.55 and lambda = 0.007738036.
library(dplyr)
glmnetfit$results %>% arrange(desc(ROC))
##   alpha       lambda       ROC      Sens      Spec      ROCSD      SensSD
## 1  0.55 0.0077380355 0.9943107 0.9962963 0.9497984 0.01140174 0.008281733
## 2  1.00 0.0077380355 0.9941966 0.9962963 0.9370968 0.01165247 0.008281733
## 3  0.10 0.0077380355 0.9941928 0.9962963 0.9372984 0.01133102 0.008281733
## 4  0.10 0.0773803551 0.9937380 0.9962963 0.9054435 0.01300793 0.008281733
## 5  0.55 0.0773803551 0.9931533 0.9962963 0.8741935 0.01334815 0.008281733
## 6  0.10 0.0007738036 0.9931304 0.9850454 0.9560484 0.01047298 0.008361688
## 7  0.55 0.0007738036 0.9930087 0.9850454 0.9497984 0.01042079 0.008361688
## 8  1.00 0.0007738036 0.9921904 0.9776380 0.9435484 0.01067464 0.008205464
## 9  1.00 0.0773803551 0.9907960 0.9925926 0.8614919 0.01207393 0.016563466
##       SpecSD
## 1 0.03550048
## 2 0.02211547
## 3 0.03100024
## 4 0.02354861
## 5 0.04423095
## 6 0.03554482
## 7 0.03550048
## 8 0.04059259
## 9 0.04254582
my_trainControl<- trainControl(method = "repeatedcv",number = 10,classProbs = TRUE,summaryFunction = twoClassSummary)
rffit <- train(diagnosis ~ ., data = training, method = "rf", trControl = fitControl, verbose = FALSE, metric = "ROC")
rffit
## Random Forest 
## 
## 427 samples
##  30 predictor
##   2 classes: 'B', 'M' 
## 
## No pre-processing
## Resampling: Cross-Validated (5 fold, repeated 1 times) 
## Summary of sample sizes: 342, 342, 341, 342, 341 
## Resampling results across tuning parameters:
## 
##   mtry  ROC        Sens       Spec     
##    2    0.9936561  0.9777079  0.9431452
##   16    0.9921875  0.9628232  0.9493952
##   30    0.9908927  0.9702306  0.9493952
## 
## ROC was used to select the optimal model using the largest value.
## The final value used for the model was mtry = 2.
rffit$results %>% arrange(desc(ROC))
##   mtry       ROC      Sens      Spec       ROCSD     SensSD     SpecSD
## 1    2 0.9936561 0.9777079 0.9431452 0.007707757 0.02413230 0.02724200
## 2   16 0.9921875 0.9628232 0.9493952 0.008416396 0.03928495 0.02914161
## 3   30 0.9908927 0.9702306 0.9493952 0.009441040 0.02813250 0.02914161
library(lubridate)
## 
## 다음의 패키지를 부착합니다: 'lubridate'
## The following objects are masked from 'package:base':
## 
##     date, intersect, setdiff, union
library(dplyr)
#install.packages("nycflights13")
library(nycflights13)

today()
## [1] "2024-02-01"
now()
## [1] "2024-02-01 09:35:48 KST"
ymd("2023-01-31")
## [1] "2023-01-31"
mdy("january 1st, 2023")
## [1] "2023-01-01"
dmy("31-jan-2023")
## [1] "2023-01-31"
ymd(20230131)
## [1] "2023-01-31"
ymd_hms("2017-01-31 20:11:59")
## [1] "2017-01-31 20:11:59 UTC"
mdy_hm("01/31/2017 08:01")
## [1] "2017-01-31 08:01:00 UTC"
data("flights")
glimpse(flights)
## Rows: 336,776
## Columns: 19
## $ year           <int> 2013, 2013, 2013, 2013, 2013, 2013, 2013, 2013, 2013, 2…
## $ month          <int> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1…
## $ day            <int> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1…
## $ dep_time       <int> 517, 533, 542, 544, 554, 554, 555, 557, 557, 558, 558, …
## $ sched_dep_time <int> 515, 529, 540, 545, 600, 558, 600, 600, 600, 600, 600, …
## $ dep_delay      <dbl> 2, 4, 2, -1, -6, -4, -5, -3, -3, -2, -2, -2, -2, -2, -1…
## $ arr_time       <int> 830, 850, 923, 1004, 812, 740, 913, 709, 838, 753, 849,…
## $ sched_arr_time <int> 819, 830, 850, 1022, 837, 728, 854, 723, 846, 745, 851,…
## $ arr_delay      <dbl> 11, 20, 33, -18, -25, 12, 19, -14, -8, 8, -2, -3, 7, -1…
## $ carrier        <chr> "UA", "UA", "AA", "B6", "DL", "UA", "B6", "EV", "B6", "…
## $ flight         <int> 1545, 1714, 1141, 725, 461, 1696, 507, 5708, 79, 301, 4…
## $ tailnum        <chr> "N14228", "N24211", "N619AA", "N804JB", "N668DN", "N394…
## $ origin         <chr> "EWR", "LGA", "JFK", "JFK", "LGA", "EWR", "EWR", "LGA",…
## $ dest           <chr> "IAH", "IAH", "MIA", "BQN", "ATL", "ORD", "FLL", "IAD",…
## $ air_time       <dbl> 227, 227, 160, 183, 116, 150, 158, 53, 140, 138, 149, 1…
## $ distance       <dbl> 1400, 1416, 1089, 1576, 762, 719, 1065, 229, 944, 733, …
## $ hour           <dbl> 5, 5, 5, 5, 6, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 6, 6, 6…
## $ minute         <dbl> 15, 29, 40, 45, 0, 58, 0, 0, 0, 0, 0, 0, 0, 0, 0, 59, 0…
## $ time_hour      <dttm> 2013-01-01 05:00:00, 2013-01-01 05:00:00, 2013-01-01 0…
flights %>% select(year, month, day, hour, minute)
## # A tibble: 336,776 × 5
##     year month   day  hour minute
##    <int> <int> <int> <dbl>  <dbl>
##  1  2013     1     1     5     15
##  2  2013     1     1     5     29
##  3  2013     1     1     5     40
##  4  2013     1     1     5     45
##  5  2013     1     1     6      0
##  6  2013     1     1     5     58
##  7  2013     1     1     6      0
##  8  2013     1     1     6      0
##  9  2013     1     1     6      0
## 10  2013     1     1     6      0
## # ℹ 336,766 more rows
flights %>% 
  select(year, month, day, hour, minute) %>% 
  mutate(departure = make_datetime(year, month, day, hour, minute))
## # A tibble: 336,776 × 6
##     year month   day  hour minute departure          
##    <int> <int> <int> <dbl>  <dbl> <dttm>             
##  1  2013     1     1     5     15 2013-01-01 05:15:00
##  2  2013     1     1     5     29 2013-01-01 05:29:00
##  3  2013     1     1     5     40 2013-01-01 05:40:00
##  4  2013     1     1     5     45 2013-01-01 05:45:00
##  5  2013     1     1     6      0 2013-01-01 06:00:00
##  6  2013     1     1     5     58 2013-01-01 05:58:00
##  7  2013     1     1     6      0 2013-01-01 06:00:00
##  8  2013     1     1     6      0 2013-01-01 06:00:00
##  9  2013     1     1     6      0 2013-01-01 06:00:00
## 10  2013     1     1     6      0 2013-01-01 06:00:00
## # ℹ 336,766 more rows
make_datetime_100 <- function(year, month, day, time) {
  make_datetime(year, month, day, time %/% 100, time %% 100) 
}

flights %>% 
  filter(!is.na(dep_time)|!is.na(arr_time)) %>% 
  mutate(
    dep_time = make_datetime_100(year, month, day, dep_time), 
    arr_time = make_datetime_100(year, month, day, arr_time),
    sched_dep_time = make_datetime_100(year, month, day, sched_dep_time), 
    sched_arr_time = make_datetime_100(year, month, day, sched_arr_time))%>%
  select(origin, dest, ends_with("delay"), ends_with("time"))
## # A tibble: 328,521 × 9
##    origin dest  dep_delay arr_delay dep_time            sched_dep_time     
##    <chr>  <chr>     <dbl>     <dbl> <dttm>              <dttm>             
##  1 EWR    IAH           2        11 2013-01-01 05:17:00 2013-01-01 05:15:00
##  2 LGA    IAH           4        20 2013-01-01 05:33:00 2013-01-01 05:29:00
##  3 JFK    MIA           2        33 2013-01-01 05:42:00 2013-01-01 05:40:00
##  4 JFK    BQN          -1       -18 2013-01-01 05:44:00 2013-01-01 05:45:00
##  5 LGA    ATL          -6       -25 2013-01-01 05:54:00 2013-01-01 06:00:00
##  6 EWR    ORD          -4        12 2013-01-01 05:54:00 2013-01-01 05:58:00
##  7 EWR    FLL          -5        19 2013-01-01 05:55:00 2013-01-01 06:00:00
##  8 LGA    IAD          -3       -14 2013-01-01 05:57:00 2013-01-01 06:00:00
##  9 JFK    MCO          -3        -8 2013-01-01 05:57:00 2013-01-01 06:00:00
## 10 LGA    ORD          -2         8 2013-01-01 05:58:00 2013-01-01 06:00:00
## # ℹ 328,511 more rows
## # ℹ 3 more variables: arr_time <dttm>, sched_arr_time <dttm>, air_time <dbl>
datetime <- ymd_hms("2023-01-31 10:30:20") 
year(datetime)
## [1] 2023
month(datetime)
## [1] 1
mday(datetime)
## [1] 31
yday(datetime)
## [1] 31
wday(datetime)
## [1] 3
getwd()
## [1] "C:/data/source data"
setwd("C:/data/source data")
df<-read.csv("netflix.csv")
df$y2<-parse_date_time(df$date_added, orders = c("mdy","dmy"),train=F) 
df %>% filter(country=="United Kingdom") %>% 
  filter(y2>='2018-01-01'&y2<='2018-01-31')
##   show_id    type                                        title        director
## 1   s5058 TV Show                                  Retribution                
## 2   s5075   Movie                          Bad Day for the Cut     Chris Baugh
## 3   s5098 TV Show                                     Lovesick                
## 4   s7399   Movie   Manolo: The Boy Who Made Shoes for Lizards Michael Roberts
## 5   s8358 TV Show                             The Inbetweeners                
## 6   s8620   Movie Treasures from the Wreck of the Unbelievable   Sam Hobkinson
##                                                                                                                                                                            cast
## 1                         Georgina Campbell, Joe Dempsie, Adrian Edmondson, Steve Evets, Laura Fraser, Julie Graham, John Lynch, Gary Lewis, Juliet Stevenson, Joanna Vanderham
## 2                        Nigel O'Neill, Susan Lynch, J?zef Pawlowski, Stuart Graham, David Pearse, Brian Milligan, Anna Prochniak, Stella McCusker, Ian McElhinney, Lalor Roddy
## 3                                                                  Johnny Flynn, Antonia Thomas, Daniel Ings, Hannah Britland, Joshua McGuire, Richard Thomson, Jessica Ellerby
## 4 Manolo Blahnik, Anna Wintour, Andr? Leon Talley, Paloma Picasso, Candace Bushnell, Iman, Rihanna, Naomi Campbell, Isaac Mizrahi, Rupert Everett, Sofia Coppola, John Galliano
## 5                     Simon Bird, James Buckley, Blake Harrison, Joe Thomas, Greg Davies, Emily Head, Martin Trenaman, Belinda Stewart-Wilson, Robin Weaver, Henry Lloyd-Hughes
## 6                                                                                                                                                                              
##          country       date_added release_year rating  duration
## 1 United Kingdom        30-Jan-18         2016  TV-MA  1 Season
## 2 United Kingdom        18-Jan-18         2017  TV-MA    99 min
## 3 United Kingdom        01-Jan-18         2018  TV-MA 3 Seasons
## 4 United Kingdom        15-Jan-18         2017  TV-MA    89 min
## 5 United Kingdom  January 1, 2018         2010  TV-MA 3 Seasons
## 6 United Kingdom        01-Jan-18         2017   TV-G    82 min
##                                                     listed_in         y2
## 1    British TV Shows, Crime TV Shows, International TV Shows 2018-01-30
## 2         Independent Movies, International Movies, Thrillers 2018-01-18
## 3 British TV Shows, International TV Shows, Romantic TV Shows 2018-01-01
## 4                         Documentaries, International Movies 2018-01-15
## 5                               British TV Shows, TV Comedies 2018-01-01
## 6                 Documentaries, Dramas, International Movies 2018-01-01
#df %>% filter(country=="United Kingdom") %>% count(date_added)

library(plyr)
## ------------------------------------------------------------------------------
## You have loaded plyr after dplyr - this is likely to cause problems.
## If you need functions from both plyr and dplyr, please load plyr first, then dplyr:
## library(plyr); library(dplyr)
## ------------------------------------------------------------------------------
## 
## 다음의 패키지를 부착합니다: 'plyr'
## The following objects are masked from 'package:dplyr':
## 
##     arrange, count, desc, failwith, id, mutate, rename, summarise,
##     summarize
df<-read.csv("Data1.csv")
df$Gender<-as.factor(df$Gender)
df$Gender<-revalue(df$Gender,replace = c("0"="female","1"="male"))
glimpse(df)
## Rows: 1,925
## Columns: 27
## $ X         <int> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 1…
## $ Q1        <int> 4, 4, 4, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, …
## $ Q2        <int> 4, 4, 4, 4, 4, 4, 2, 2, 4, 4, 4, 4, 4, 2, 4, 4, 2, 4, 2, 2, …
## $ Q3        <int> 2, 4, 4, 4, 4, 4, 4, 4, 4, 2, 4, 2, 4, 4, 4, 4, 4, 3, 2, 3, …
## $ Q4        <int> 3, 4, 4, 4, 4, 4, 4, 4, 4, 2, 4, 4, 4, 2, 4, 4, 4, 2, 2, 4, …
## $ Q5        <int> 4, 4, 2, 4, 4, 4, 4, 4, 2, 4, 4, 2, 4, 4, 4, 4, 4, 3, 1, 2, …
## $ Q6        <int> 2, 3, 4, 4, 4, 4, 4, 4, 1, 2, 2, 2, 4, 4, 3, 5, 2, 2, 1, 4, …
## $ Q7        <int> 2, 2, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 5, 4, 4, 5, 4, 3, 4, 4, …
## $ Q8        <int> 4, 4, 4, 4, 4, 4, 5, 5, 2, 2, 4, 4, 4, 4, 3, 5, 4, 2, 4, 4, …
## $ Q9        <int> 4, 4, 4, 4, 2, 4, 5, 5, 3, 4, 4, 4, 2, 2, 4, 5, 2, 4, 2, 4, …
## $ Q10       <int> 4, 4, 2, 4, 4, 4, 5, 5, 2, 4, 2, 4, 4, 4, 3, 4, 4, 3, 2, 3, …
## $ Q11       <int> 4, 4, 4, 4, 4, 4, 5, 5, 4, 4, 4, 3, 4, 4, 4, 4, 5, 4, 3, 3, …
## $ Q12       <int> 4, 4, 4, 4, 4, 4, 5, 5, 3, 4, 4, 3, 4, 3, 3, 4, 5, 4, 4, 2, …
## $ Q13       <int> 4, 4, 4, 4, 4, 4, 5, 5, 4, 4, 4, 4, 2, 4, 4, 4, 5, 4, 4, 4, …
## $ Q14       <int> 4, 4, 4, 4, 4, 4, 5, 5, 5, 4, 4, 4, 3, 4, 5, 4, 5, 4, 4, 4, …
## $ Q15       <int> 4, 4, 3, 4, 4, 4, 4, 2, 3, 4, 4, 3, 1, 4, 4, 4, 5, 4, 4, 4, …
## $ Q16       <int> 4, 4, 4, 4, 4, 4, 5, 2, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 4, 4, …
## $ Q17       <int> 4, 3, 4, 4, 4, 4, 2, 2, 4, 4, 4, 4, 3, 2, 4, 5, 4, 4, 3, 4, …
## $ Q18       <int> 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 2, 4, 4, 4, …
## $ Q19       <int> 4, 2, 4, 4, 4, 4, 4, 2, 4, 2, 4, 4, 1, 4, 4, 4, 5, 4, 2, 3, …
## $ Q20       <int> 4, 1, 3, 4, 4, 4, 4, 2, 4, 2, 4, 4, 4, 2, 4, 5, 5, 4, 2, 4, …
## $ Gender    <fct> female, female, female, female, female, female, female, fema…
## $ EDU       <int> 1, 1, 2, 1, 2, 1, 1, 1, 4, 3, 2, 1, 1, 3, 3, 2, 1, 1, 1, 4, …
## $ BF        <dbl> 3.4, 4.0, 3.6, 4.2, 4.0, 4.0, 3.6, 3.6, 3.6, 3.2, 4.0, 3.2, …
## $ BM        <dbl> 3.2, 3.4, 3.6, 4.0, 3.6, 4.0, 4.6, 4.6, 2.2, 3.2, 3.2, 3.6, …
## $ Happiness <dbl> 4.0, 4.0, 3.8, 4.0, 4.0, 4.0, 4.8, 4.4, 3.8, 4.0, 4.0, 3.4, …
## $ Peace     <dbl> 4.0, 2.8, 3.8, 4.0, 4.0, 4.0, 3.8, 2.4, 4.0, 3.2, 4.0, 3.9, …
table(df$Gender)
## 
## female   male 
##   1136    789
# 필요한 패키지 설치 및 로드
library(caret)

# 1. 데이터 불러오기
data <- read.csv("Data1.csv")  # 파일 경로에 맞게 수정

# 2. 목표변수 Gender를 Factor형으로 변환
data$Gender <- as.factor(data$Gender)

# 3. 데이터 분할 (학습 데이터와 테스트 데이터로 분할)
set.seed(123)
train_index <- createDataPartition(data$Gender, p = 0.8, list = FALSE)
train_data <- data[train_index, ]
test_data <- data[-train_index, ]

# 4. 분류 모델 학습 (랜덤 포레스트)
model <- randomForest(Gender ~ ., data = train_data)

# 5. 테스트 데이터에 대한 예측
predicted <- predict(model, newdata = test_data)

# 6. 혼동 행렬 출력
conf_matrix <- confusionMatrix(predicted, reference = test_data$Gender)
print(conf_matrix)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction   0   1
##          0 183  91
##          1  44  66
##                                           
##                Accuracy : 0.6484          
##                  95% CI : (0.5984, 0.6962)
##     No Information Rate : 0.5911          
##     P-Value [Acc > NIR] : 0.01233         
##                                           
##                   Kappa : 0.2375          
##                                           
##  Mcnemar's Test P-Value : 7.525e-05       
##                                           
##             Sensitivity : 0.8062          
##             Specificity : 0.4204          
##          Pos Pred Value : 0.6679          
##          Neg Pred Value : 0.6000          
##              Prevalence : 0.5911          
##          Detection Rate : 0.4766          
##    Detection Prevalence : 0.7135          
##       Balanced Accuracy : 0.6133          
##                                           
##        'Positive' Class : 0               
##