getwd()
## [1] "C:/data"
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
library(caret)
## 필요한 패키지를 로딩중입니다: ggplot2
## 필요한 패키지를 로딩중입니다: lattice
data(iris)
glimpse(iris)
## Rows: 150
## Columns: 5
## $ Sepal.Length <dbl> 5.1, 4.9, 4.7, 4.6, 5.0, 5.4, 4.6, 5.0, 4.4, 4.9, 5.4, 4.…
## $ Sepal.Width  <dbl> 3.5, 3.0, 3.2, 3.1, 3.6, 3.9, 3.4, 3.4, 2.9, 3.1, 3.7, 3.…
## $ Petal.Length <dbl> 1.4, 1.4, 1.3, 1.5, 1.4, 1.7, 1.4, 1.5, 1.4, 1.5, 1.5, 1.…
## $ Petal.Width  <dbl> 0.2, 0.2, 0.2, 0.2, 0.2, 0.4, 0.3, 0.2, 0.2, 0.1, 0.2, 0.…
## $ Species      <fct> setosa, setosa, setosa, setosa, setosa, setosa, setosa, s…
iris %>% count(Species)
##      Species  n
## 1     setosa 50
## 2 versicolor 50
## 3  virginica 50
library(randomForest)
## Warning: 패키지 'randomForest'는 R 버전 4.3.2에서 작성되었습니다
## randomForest 4.7-1.1
## Type rfNews() to see new features/changes/bug fixes.
## 
## 다음의 패키지를 부착합니다: 'randomForest'
## The following object is masked from 'package:ggplot2':
## 
##     margin
## The following object is masked from 'package:dplyr':
## 
##     combine
data(iris)

model<-randomForest(Species~.,data=iris)
model
## 
## Call:
##  randomForest(formula = Species ~ ., data = iris) 
##                Type of random forest: classification
##                      Number of trees: 500
## No. of variables tried at each split: 2
## 
##         OOB estimate of  error rate: 4.67%
## Confusion matrix:
##            setosa versicolor virginica class.error
## setosa         50          0         0        0.00
## versicolor      0         47         3        0.06
## virginica       0          4        46        0.08
model2<-randomForest(Species~.,data=iris,
                      ntree=300, mtry=4, na.action = na.omit)
#ntree 의사결정의 수
#mtry 변수의 수
#na.action = na.omit, 결측값 제외

model2
## 
## Call:
##  randomForest(formula = Species ~ ., data = iris, ntree = 300,      mtry = 4, na.action = na.omit) 
##                Type of random forest: classification
##                      Number of trees: 300
## No. of variables tried at each split: 4
## 
##         OOB estimate of  error rate: 4%
## Confusion matrix:
##            setosa versicolor virginica class.error
## setosa         50          0         0        0.00
## versicolor      0         47         3        0.06
## virginica       0          3        47        0.06
#중요변수로 랜덤포레스트 생성
model3<-randomForest(Species~., data=iris,
                     importance=TRUE, na.action = na.omit)
importance(model3)
##                 setosa versicolor virginica MeanDecreaseAccuracy
## Sepal.Length  7.349367   8.471848  7.741170            11.256309
## Sepal.Width   5.217300   1.699296  5.287565             6.203037
## Petal.Length 22.047759  33.611371 27.523267            32.794805
## Petal.Width  21.848145  31.166812 29.943448            32.222157
##              MeanDecreaseGini
## Sepal.Length        10.440866
## Sepal.Width          2.445733
## Petal.Length        42.769753
## Petal.Width         43.606448
varImpPlot(model3)

#최적의 파라미터 찾기
ntree<-c(400,500,600)
mtry<-c(2:4)

param<-data.frame(n=ntree,m=mtry)

for(i in param$n){
  cat('ntree=',i, '\n')
  for(j in param$m){
    cat('mtry=',j, '\n')
    model_iris<-randomForest(Species~., data=iris,
                             ntree=i, mtry=j, na.action = na.omit)
    print(model_iris)
  }
}
## ntree= 400 
## mtry= 2 
## 
## Call:
##  randomForest(formula = Species ~ ., data = iris, ntree = i, mtry = j,      na.action = na.omit) 
##                Type of random forest: classification
##                      Number of trees: 400
## No. of variables tried at each split: 2
## 
##         OOB estimate of  error rate: 4.67%
## Confusion matrix:
##            setosa versicolor virginica class.error
## setosa         50          0         0        0.00
## versicolor      0         47         3        0.06
## virginica       0          4        46        0.08
## mtry= 3 
## 
## Call:
##  randomForest(formula = Species ~ ., data = iris, ntree = i, mtry = j,      na.action = na.omit) 
##                Type of random forest: classification
##                      Number of trees: 400
## No. of variables tried at each split: 3
## 
##         OOB estimate of  error rate: 4.67%
## Confusion matrix:
##            setosa versicolor virginica class.error
## setosa         50          0         0        0.00
## versicolor      0         47         3        0.06
## virginica       0          4        46        0.08
## mtry= 4 
## 
## Call:
##  randomForest(formula = Species ~ ., data = iris, ntree = i, mtry = j,      na.action = na.omit) 
##                Type of random forest: classification
##                      Number of trees: 400
## No. of variables tried at each split: 4
## 
##         OOB estimate of  error rate: 4%
## Confusion matrix:
##            setosa versicolor virginica class.error
## setosa         50          0         0        0.00
## versicolor      0         47         3        0.06
## virginica       0          3        47        0.06
## ntree= 500 
## mtry= 2 
## 
## Call:
##  randomForest(formula = Species ~ ., data = iris, ntree = i, mtry = j,      na.action = na.omit) 
##                Type of random forest: classification
##                      Number of trees: 500
## No. of variables tried at each split: 2
## 
##         OOB estimate of  error rate: 5.33%
## Confusion matrix:
##            setosa versicolor virginica class.error
## setosa         50          0         0        0.00
## versicolor      0         47         3        0.06
## virginica       0          5        45        0.10
## mtry= 3 
## 
## Call:
##  randomForest(formula = Species ~ ., data = iris, ntree = i, mtry = j,      na.action = na.omit) 
##                Type of random forest: classification
##                      Number of trees: 500
## No. of variables tried at each split: 3
## 
##         OOB estimate of  error rate: 4%
## Confusion matrix:
##            setosa versicolor virginica class.error
## setosa         50          0         0        0.00
## versicolor      0         47         3        0.06
## virginica       0          3        47        0.06
## mtry= 4 
## 
## Call:
##  randomForest(formula = Species ~ ., data = iris, ntree = i, mtry = j,      na.action = na.omit) 
##                Type of random forest: classification
##                      Number of trees: 500
## No. of variables tried at each split: 4
## 
##         OOB estimate of  error rate: 4.67%
## Confusion matrix:
##            setosa versicolor virginica class.error
## setosa         50          0         0        0.00
## versicolor      0         47         3        0.06
## virginica       0          4        46        0.08
## ntree= 600 
## mtry= 2 
## 
## Call:
##  randomForest(formula = Species ~ ., data = iris, ntree = i, mtry = j,      na.action = na.omit) 
##                Type of random forest: classification
##                      Number of trees: 600
## No. of variables tried at each split: 2
## 
##         OOB estimate of  error rate: 4.67%
## Confusion matrix:
##            setosa versicolor virginica class.error
## setosa         50          0         0        0.00
## versicolor      0         47         3        0.06
## virginica       0          4        46        0.08
## mtry= 3 
## 
## Call:
##  randomForest(formula = Species ~ ., data = iris, ntree = i, mtry = j,      na.action = na.omit) 
##                Type of random forest: classification
##                      Number of trees: 600
## No. of variables tried at each split: 3
## 
##         OOB estimate of  error rate: 4%
## Confusion matrix:
##            setosa versicolor virginica class.error
## setosa         50          0         0        0.00
## versicolor      0         47         3        0.06
## virginica       0          3        47        0.06
## mtry= 4 
## 
## Call:
##  randomForest(formula = Species ~ ., data = iris, ntree = i, mtry = j,      na.action = na.omit) 
##                Type of random forest: classification
##                      Number of trees: 600
## No. of variables tried at each split: 4
## 
##         OOB estimate of  error rate: 4%
## Confusion matrix:
##            setosa versicolor virginica class.error
## setosa         50          0         0        0.00
## versicolor      0         47         3        0.06
## virginica       0          3        47        0.06
library(gapminder)
library(dplyr)

data("gapminder")
glimpse(gapminder)
## Rows: 1,704
## Columns: 6
## $ country   <fct> "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", …
## $ continent <fct> Asia, Asia, Asia, Asia, Asia, Asia, Asia, Asia, Asia, Asia, …
## $ year      <int> 1952, 1957, 1962, 1967, 1972, 1977, 1982, 1987, 1992, 1997, …
## $ lifeExp   <dbl> 28.801, 30.332, 31.997, 34.020, 36.088, 38.438, 39.854, 40.8…
## $ pop       <int> 8425333, 9240934, 10267083, 11537966, 13079460, 14880372, 12…
## $ gdpPercap <dbl> 779.4453, 820.8530, 853.1007, 836.1971, 739.9811, 786.1134, …
gapminder %>% count(year)
## # A tibble: 12 × 2
##     year     n
##    <int> <int>
##  1  1952   142
##  2  1957   142
##  3  1962   142
##  4  1967   142
##  5  1972   142
##  6  1977   142
##  7  1982   142
##  8  1987   142
##  9  1992   142
## 10  1997   142
## 11  2002   142
## 12  2007   142
gapminder<-gapminder %>%  filter(year=='2007') %>% 
  mutate(totalGdp=pop*gdpPercap)

gapminder %>% filter(year=='2007') %>% 
  mutate(totalGdp=pop*gdpPercap) %>% 
  summarize(avg=mean(totalGdp))
## # A tibble: 1 × 1
##             avg
##           <dbl>
## 1 409220666999.
gapminder %>% filter(totalGdp >= 409220666999) %>% NROW()
## [1] 25
df<-gapminder %>% filter(totalGdp >= 409220666999) %>% arrange(desc(totalGdp))


data("gapminder")


gapminder<-gapminder %>%  filter(year=='1997') %>% 
  mutate(totalGdp=pop*gdpPercap)

gapminder %>% filter(year=='1997') %>% 
  mutate(totalGdp=pop*gdpPercap) %>% 
  summarize(avg=mean(totalGdp))
## # A tibble: 1 × 1
##             avg
##           <dbl>
## 1 288775189215.
gapminder %>% filter(totalGdp >= 288775189215) %>% NROW()
## [1] 24
df<-gapminder %>% filter(totalGdp >= 288775189215) %>% arrange(desc(totalGdp))