#기본내장 데이터를 선정해서 기본 dplyr 10개 반복연습해
#구글-국가통계포털-#가해자 연령층별 교통사고 csv 받아서 "ta1" 이름 바꿔
#원본 파일명은 분석효율이 떨어져, 이름 바꿔 저장
getwd()
## [1] "C:/data"
setwd("c:/data")
getwd()
## [1] "c:/data"
ls() # 리스트 점검
## character(0)
rm(list=ls()) # 리슽트 제거

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
#열변수값 한글 오류생김, 옵션 추가해줘야해
df<-read.csv("ta1.csv",fileEncoding="euc-kr")
View(df) #확인해봐

#매일 특정데이터 반복연습, dplyr 매일 공공데이터 뽑아와서 변형 2 30분 매일
#어떤 데이터도 dplyr이 무력화시킬 수 있어. 

names(df) #변수 이름이 뭐야?
## [1] "가해자연령층별.1." "월별.1."           "X2022"            
## [4] "X2022.1"           "X2022.2"
df %>% rename(month=월별.1.,
              사고건수=X2022, 
              사망자수=X2022.1,
              연령층=가해자연령층별.1., 
              부상자수=X2022.2)
##                연령층   month      사고건수      사망자수      부상자수
## 1   가해자연령층별(1) 월별(1) 사고건수 (건) 사망자수 (명) 부상자수 (명)
## 2            20세이하    전체          6508            72          8863
## 3            20세이하     1월           435             6           633
## 4            20세이하     2월           357             2           505
## 5            20세이하     3월           473             3           678
## 6            20세이하     4월           580             7           810
## 7            20세이하     5월           713             6           955
## 8            20세이하     6월           668             5           877
## 9            20세이하     7월           639             6           847
## 10           20세이하     8월           557             7           735
## 11           20세이하     9월           609             8           808
## 12           20세이하    10월           618             8           805
## 13           20세이하    11월           532             8           724
## 14           20세이하    12월           327             6           486
## 15            21-30세    전체         26904           335         39706
## 16            21-30세     1월          2307            31          3470
## 17            21-30세     2월          1787            22          2614
## 18            21-30세     3월          1950            26          2793
## 19            21-30세     4월          2310            16          3460
## 20            21-30세     5월          2503            29          3719
## 21            21-30세     6월          2182            29          3209
## 22            21-30세     7월          2368            32          3546
## 23            21-30세     8월          2322            30          3382
## 24            21-30세     9월          2276            28          3419
## 25            21-30세    10월          2376            38          3442
## 26            21-30세    11월          2228            26          3209
## 27            21-30세    12월          2295            28          3443
## 28            31-40세    전체         28402           317         41287
## 29            31-40세     1월          2336            28          3418
## 30            31-40세     2월          2001            30          2903
## 31            31-40세     3월          1969            19          2820
## 32            31-40세     4월          2409            29          3534
## 33            31-40세     5월          2525            26          3613
## 34            31-40세     6월          2341            22          3446
## 35            31-40세     7월          2463            22          3615
## 36            31-40세     8월          2330            30          3428
## 37            31-40세     9월          2268            25          3285
## 38            31-40세    10월          2589            32          3750
## 39            31-40세    11월          2489            23          3579
## 40            31-40세    12월          2682            31          3896
## 41            41-50세    전체         33915           409         48389
## 42            41-50세     1월          2939            33          4156
## 43            41-50세     2월          2197            20          3086
## 44            41-50세     3월          2391            27          3302
## 45            41-50세     4월          2805            29          4013
## 46            41-50세     5월          3096            34          4321
## 47            41-50세     6월          2760            37          3878
## 48            41-50세     7월          2930            44          4296
## 49            41-50세     8월          2776            30          4056
## 50            41-50세     9월          2900            37          4255
## 51            41-50세    10월          3083            38          4543
## 52            41-50세    11월          2994            43          4182
## 53            41-50세    12월          3044            37          4301
## 54            51-60세    전체         44581           570         63632
## 55            51-60세     1월          3683            40          5243
## 56            51-60세     2월          2849            34          4085
## 57            51-60세     3월          3191            37          4345
## 58            51-60세     4월          3772            56          5385
## 59            51-60세     5월          3989            47          5745
## 60            51-60세     6월          3733            50          5266
## 61            51-60세     7월          3747            49          5414
## 62            51-60세     8월          3677            44          5400
## 63            51-60세     9월          3872            61          5485
## 64            51-60세    10월          4156            53          6083
## 65            51-60세    11월          4001            52          5554
## 66            51-60세    12월          3911            47          5627
## 67            61-64세    전체         19160           297         27566
## 68            61-64세     1월          1494            19          2178
## 69            61-64세     2월          1112            16          1578
## 70            61-64세     3월          1211            23          1658
## 71            61-64세     4월          1535            20          2309
## 72            61-64세     5월          1735            23          2503
## 73            61-64세     6월          1691            29          2432
## 74            61-64세     7월          1705            24          2472
## 75            61-64세     8월          1681            29          2477
## 76            61-64세     9월          1751            27          2464
## 77            61-64세    10월          1855            43          2679
## 78            61-64세    11월          1703            27          2430
## 79            61-64세    12월          1687            17          2386
## 80            65-70세    전체         19399           349         27792
## 81            65-70세     1월          1395            17          1973
## 82            65-70세     2월          1042            14          1478
## 83            65-70세     3월          1234            26          1660
## 84            65-70세     4월          1554            26          2229
## 85            65-70세     5월          1792            27          2613
## 86            65-70세     6월          1633            25          2339
## 87            65-70세     7월          1724            34          2512
## 88            65-70세     8월          1614            38          2333
## 89            65-70세     9월          1777            32          2528
## 90            65-70세    10월          1960            31          2816
## 91            65-70세    11월          1945            37          2769
## 92            65-70세    12월          1729            42          2542
## 93           71세이상    전체         15253           386         21489
## 94           71세이상     1월          1074            19          1453
## 95           71세이상     2월           845            23          1148
## 96           71세이상     3월          1018            22          1393
## 97           71세이상     4월          1296            33          1828
## 98           71세이상     5월          1453            43          2013
## 99           71세이상     6월          1257            34          1740
## 100          71세이상     7월          1324            30          1877
## 101          71세이상     8월          1306            34          1865
## 102          71세이상     9월          1483            39          2095
## 103          71세이상    10월          1647            42          2396
## 104          71세이상    11월          1443            41          1994
## 105          71세이상    12월          1107            26          1687
## 106              불명    전체          2714             0          3079
## 107              불명     1월           231             0           267
## 108              불명     2월           172             0           191
## 109              불명     3월           183             0           204
## 110              불명     4월           211             0           231
## 111              불명     5월           259             0           290
## 112              불명     6월           216             0           242
## 113              불명     7월           215             0           233
## 114              불명     8월           233             0           278
## 115              불명     9월           280             0           305
## 116              불명    10월           224             0           261
## 117              불명    11월           243             0           302
## 118              불명    12월           247             0           275
df1<-df %>% rename(month=월별.1.,사고건수=X2022, 사망자수=X2022.1,
                   연령층=가해자연령층별.1., 부상자수=X2022.2)
View(df1)
head(df1)
##              연령층   month      사고건수      사망자수      부상자수
## 1 가해자연령층별(1) 월별(1) 사고건수 (건) 사망자수 (명) 부상자수 (명)
## 2          20세이하    전체          6508            72          8863
## 3          20세이하     1월           435             6           633
## 4          20세이하     2월           357             2           505
## 5          20세이하     3월           473             3           678
## 6          20세이하     4월           580             7           810
df1 %>% slice(-1) #첫 행 날려
##       연령층 month 사고건수 사망자수 부상자수
## 1   20세이하  전체     6508       72     8863
## 2   20세이하   1월      435        6      633
## 3   20세이하   2월      357        2      505
## 4   20세이하   3월      473        3      678
## 5   20세이하   4월      580        7      810
## 6   20세이하   5월      713        6      955
## 7   20세이하   6월      668        5      877
## 8   20세이하   7월      639        6      847
## 9   20세이하   8월      557        7      735
## 10  20세이하   9월      609        8      808
## 11  20세이하  10월      618        8      805
## 12  20세이하  11월      532        8      724
## 13  20세이하  12월      327        6      486
## 14   21-30세  전체    26904      335    39706
## 15   21-30세   1월     2307       31     3470
## 16   21-30세   2월     1787       22     2614
## 17   21-30세   3월     1950       26     2793
## 18   21-30세   4월     2310       16     3460
## 19   21-30세   5월     2503       29     3719
## 20   21-30세   6월     2182       29     3209
## 21   21-30세   7월     2368       32     3546
## 22   21-30세   8월     2322       30     3382
## 23   21-30세   9월     2276       28     3419
## 24   21-30세  10월     2376       38     3442
## 25   21-30세  11월     2228       26     3209
## 26   21-30세  12월     2295       28     3443
## 27   31-40세  전체    28402      317    41287
## 28   31-40세   1월     2336       28     3418
## 29   31-40세   2월     2001       30     2903
## 30   31-40세   3월     1969       19     2820
## 31   31-40세   4월     2409       29     3534
## 32   31-40세   5월     2525       26     3613
## 33   31-40세   6월     2341       22     3446
## 34   31-40세   7월     2463       22     3615
## 35   31-40세   8월     2330       30     3428
## 36   31-40세   9월     2268       25     3285
## 37   31-40세  10월     2589       32     3750
## 38   31-40세  11월     2489       23     3579
## 39   31-40세  12월     2682       31     3896
## 40   41-50세  전체    33915      409    48389
## 41   41-50세   1월     2939       33     4156
## 42   41-50세   2월     2197       20     3086
## 43   41-50세   3월     2391       27     3302
## 44   41-50세   4월     2805       29     4013
## 45   41-50세   5월     3096       34     4321
## 46   41-50세   6월     2760       37     3878
## 47   41-50세   7월     2930       44     4296
## 48   41-50세   8월     2776       30     4056
## 49   41-50세   9월     2900       37     4255
## 50   41-50세  10월     3083       38     4543
## 51   41-50세  11월     2994       43     4182
## 52   41-50세  12월     3044       37     4301
## 53   51-60세  전체    44581      570    63632
## 54   51-60세   1월     3683       40     5243
## 55   51-60세   2월     2849       34     4085
## 56   51-60세   3월     3191       37     4345
## 57   51-60세   4월     3772       56     5385
## 58   51-60세   5월     3989       47     5745
## 59   51-60세   6월     3733       50     5266
## 60   51-60세   7월     3747       49     5414
## 61   51-60세   8월     3677       44     5400
## 62   51-60세   9월     3872       61     5485
## 63   51-60세  10월     4156       53     6083
## 64   51-60세  11월     4001       52     5554
## 65   51-60세  12월     3911       47     5627
## 66   61-64세  전체    19160      297    27566
## 67   61-64세   1월     1494       19     2178
## 68   61-64세   2월     1112       16     1578
## 69   61-64세   3월     1211       23     1658
## 70   61-64세   4월     1535       20     2309
## 71   61-64세   5월     1735       23     2503
## 72   61-64세   6월     1691       29     2432
## 73   61-64세   7월     1705       24     2472
## 74   61-64세   8월     1681       29     2477
## 75   61-64세   9월     1751       27     2464
## 76   61-64세  10월     1855       43     2679
## 77   61-64세  11월     1703       27     2430
## 78   61-64세  12월     1687       17     2386
## 79   65-70세  전체    19399      349    27792
## 80   65-70세   1월     1395       17     1973
## 81   65-70세   2월     1042       14     1478
## 82   65-70세   3월     1234       26     1660
## 83   65-70세   4월     1554       26     2229
## 84   65-70세   5월     1792       27     2613
## 85   65-70세   6월     1633       25     2339
## 86   65-70세   7월     1724       34     2512
## 87   65-70세   8월     1614       38     2333
## 88   65-70세   9월     1777       32     2528
## 89   65-70세  10월     1960       31     2816
## 90   65-70세  11월     1945       37     2769
## 91   65-70세  12월     1729       42     2542
## 92  71세이상  전체    15253      386    21489
## 93  71세이상   1월     1074       19     1453
## 94  71세이상   2월      845       23     1148
## 95  71세이상   3월     1018       22     1393
## 96  71세이상   4월     1296       33     1828
## 97  71세이상   5월     1453       43     2013
## 98  71세이상   6월     1257       34     1740
## 99  71세이상   7월     1324       30     1877
## 100 71세이상   8월     1306       34     1865
## 101 71세이상   9월     1483       39     2095
## 102 71세이상  10월     1647       42     2396
## 103 71세이상  11월     1443       41     1994
## 104 71세이상  12월     1107       26     1687
## 105     불명  전체     2714        0     3079
## 106     불명   1월      231        0      267
## 107     불명   2월      172        0      191
## 108     불명   3월      183        0      204
## 109     불명   4월      211        0      231
## 110     불명   5월      259        0      290
## 111     불명   6월      216        0      242
## 112     불명   7월      215        0      233
## 113     불명   8월      233        0      278
## 114     불명   9월      280        0      305
## 115     불명  10월      224        0      261
## 116     불명  11월      243        0      302
## 117     불명  12월      247        0      275
df2<-df1 %>% slice(-1) #df2에 저장
View(df2)
table(df2$month)
## 
## 10월 11월 12월  1월  2월  3월  4월  5월  6월  7월  8월  9월 전체 
##    9    9    9    9    9    9    9    9    9    9    9    9    9
df2 %>% filter(month!="전체") %>% glimpse() #전체값 필터해서 글림스
## Rows: 108
## Columns: 5
## $ 연령층   <chr> "20세이하", "20세이하", "20세이하", "20세이하", "20세이하", "…
## $ month    <chr> "1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월"…
## $ 사고건수 <chr> "435", "357", "473", "580", "713", "668", "639", "557", "609"…
## $ 사망자수 <chr> "6", "2", "3", "7", "6", "5", "6", "7", "8", "8", "8", "6", "…
## $ 부상자수 <chr> "633", "505", "678", "810", "955", "877", "847", "735", "808"…
#사고건수가 chr이야. 사고건수를 수치형으로 바꿔줘
df2$사고건수<-as.numeric(df2$사고건수)
glimpse(df2) #사고건수가 더블형으로 바뀐 걸 확인해
## Rows: 117
## Columns: 5
## $ 연령층   <chr> "20세이하", "20세이하", "20세이하", "20세이하", "20세이하", "…
## $ month    <chr> "전체", "1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월…
## $ 사고건수 <dbl> 6508, 435, 357, 473, 580, 713, 668, 639, 557, 609, 618, 532, …
## $ 사망자수 <chr> "72", "6", "2", "3", "7", "6", "5", "6", "7", "8", "8", "8", …
## $ 부상자수 <chr> "8863", "633", "505", "678", "810", "955", "877", "847", "735…
#어떤 상황에서도 10분 20분 내에 결과물을 프린트해서 보고=> 경쟁력



#ggplot2 패키지 데이터 시각화
#gapminder 데이터 유명해

#install.packages("gapminder")
library(gapminder)
#install.packages("ggplot2")
library(ggplot2)
#install.packages("dplyr")
library(dplyr)
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 로 버블차트 만드는 것, R로 만든 것
##기대수명이 연도별로 가면서 국가별로 변동하는 시각화 인상적
##중국의 상하이를 떼어내서 다른 국가와 비교하는 장면 인상적
##기존 직무자가 분석가에게 의뢰, 이제는 직무가도 할 수 있어야해

y<-gapminder %>% group_by(year, continent) %>% summarize(c_pop=sum(pop))
## `summarise()` has grouped output by 'year'. You can override using the
## `.groups` argument.
#갑자기 오류 왜? 위에 패키지를 다시 다 라이브러리 하니까 해결됨
head(y,20)
## # A tibble: 20 × 3
## # Groups:   year [4]
##     year continent      c_pop
##    <int> <fct>          <dbl>
##  1  1952 Africa     237640501
##  2  1952 Americas   345152446
##  3  1952 Asia      1395357351
##  4  1952 Europe     418120846
##  5  1952 Oceania     10686006
##  6  1957 Africa     264837738
##  7  1957 Americas   386953916
##  8  1957 Asia      1562780599
##  9  1957 Europe     437890351
## 10  1957 Oceania     11941976
## 11  1962 Africa     296516865
## 12  1962 Americas   433270254
## 13  1962 Asia      1696357182
## 14  1962 Europe     460355155
## 15  1962 Oceania     13283518
## 16  1967 Africa     335289489
## 17  1967 Americas   480746623
## 18  1967 Asia      1905662900
## 19  1967 Europe     481178958
## 20  1967 Oceania     14600414
plot(y$year, y$c_pop)

plot(gapminder$gdpPercap,gapminder$lifeExp, col=gapminder$continent)
#주석을 달아보자 legend
legend("bottomright", 
       legend=levels((gapminder$continent)), 
       pch=c(1:length(levels(gapminder$continent))),
       col=c(1:length(levels(y$continent))))

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, …
#ggplot
library(ggplot2)

ggplot(gapminder, aes(x=gdpPercap, y=lifeExp, col=continent))+geom_point()+scale_x_log10()

ggplot(gapminder, aes(x=gdpPercap, y=lifeExp, col=continent, size=pop))+geom_point()+scale_x_log10()

##공공기관 가시면서 이제 막대그래프 좀 그만 쓰라고 말씀드려요. 착시효과
##조직적인 문제도 있지만, 변화를 허용하지 않는것도 있어.
##정체가 돼요. 발전이 없어요.
##2년 단위로 움직여. 축약하는게 중요해. 핵심만 골격잡아 넘겨주는게 중요. 시각화


#투명도를 갖고 싶어요
ggplot(gapminder, aes(x=gdpPercap, y=lifeExp, col=continent, size=pop))+
  geom_point(alpha=0.5)+scale_x_log10()

#나는 연도별로 꺾어 보고 싶어요. 마지막 옵션
ggplot(gapminder, aes(x=gdpPercap, y=lifeExp, col=continent, size=pop))+
  geom_point(alpha=0.5)+scale_x_log10()+facet_wrap((~year))

##교통사고 연도별로 회의할 때 띄우면 얼마나 좋을까요? 생각하셔야해요.

#1952년 아시아대륙의인구분포에서각국가의순위를매겨보자
gapminder %>% filter(year==1952 & continent=="Asia") %>% 
  ggplot(aes(reorder(country,pop),pop))+geom_bar(stat = "identity")+coord_flip()

##여러분 Rpubs 잘 만들면 조회수 올라가서 구글에서 올라갈거에요
##구글에 'rpubs ggplot2' 쳐보면 남이 한 거 올라와있어

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, …
View(gapminder)
gapminder %>% filter(country=="Korea, Rep.") %>% 
  ggplot(aes(year,lifeExp,col=country)) +
  geom_point()+geom_line()

summary(gapminder$lifeExp)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##   23.60   48.20   60.71   59.47   70.85   82.60
##구글에 sheet dplyr in r 검색, 컬러프린트 해서 사무실에 놔
##ggplot2 이것도 

##내일 캐롯 패키지 소개합니다. 아직 우리나라에 제대로 된 설명 없어. 새로 생긴거 232개 알고리즘
##캐롯 패키지 머신러닝


#오후수업
#파생변수 생성
data(cars)
glimpse(cars)
## Rows: 50
## Columns: 2
## $ speed <dbl> 4, 4, 7, 7, 8, 9, 10, 10, 10, 11, 11, 12, 12, 12, 12, 13, 13, 13…
## $ dist  <dbl> 2, 10, 4, 22, 16, 10, 18, 26, 34, 17, 28, 14, 20, 24, 28, 26, 34…
summary(cars)
##      speed           dist       
##  Min.   : 4.0   Min.   :  2.00  
##  1st Qu.:12.0   1st Qu.: 26.00  
##  Median :15.0   Median : 36.00  
##  Mean   :15.4   Mean   : 42.98  
##  3rd Qu.:19.0   3rd Qu.: 56.00  
##  Max.   :25.0   Max.   :120.00
cars1 <- cars %>% mutate(violation=ifelse(cars$speed>15.4,"fast","slow"))
cars1
##    speed dist violation
## 1      4    2      slow
## 2      4   10      slow
## 3      7    4      slow
## 4      7   22      slow
## 5      8   16      slow
## 6      9   10      slow
## 7     10   18      slow
## 8     10   26      slow
## 9     10   34      slow
## 10    11   17      slow
## 11    11   28      slow
## 12    12   14      slow
## 13    12   20      slow
## 14    12   24      slow
## 15    12   28      slow
## 16    13   26      slow
## 17    13   34      slow
## 18    13   34      slow
## 19    13   46      slow
## 20    14   26      slow
## 21    14   36      slow
## 22    14   60      slow
## 23    14   80      slow
## 24    15   20      slow
## 25    15   26      slow
## 26    15   54      slow
## 27    16   32      fast
## 28    16   40      fast
## 29    17   32      fast
## 30    17   40      fast
## 31    17   50      fast
## 32    18   42      fast
## 33    18   56      fast
## 34    18   76      fast
## 35    18   84      fast
## 36    19   36      fast
## 37    19   46      fast
## 38    19   68      fast
## 39    20   32      fast
## 40    20   48      fast
## 41    20   52      fast
## 42    20   56      fast
## 43    20   64      fast
## 44    22   66      fast
## 45    23   54      fast
## 46    24   70      fast
## 47    24   92      fast
## 48    24   93      fast
## 49    24  120      fast
## 50    25   85      fast
glimpse(cars1)
## Rows: 50
## Columns: 3
## $ speed     <dbl> 4, 4, 7, 7, 8, 9, 10, 10, 10, 11, 11, 12, 12, 12, 12, 13, 13…
## $ dist      <dbl> 2, 10, 4, 22, 16, 10, 18, 26, 34, 17, 28, 14, 20, 24, 28, 26…
## $ violation <chr> "slow", "slow", "slow", "slow", "slow", "slow", "slow", "slo…
#그룹바이 서머라이즈가 습관적으로 기억나야해, 연속적인걸 쪼개서 볼줄 알아야해
cars1 %>% group_by(violation) %>% summarise(p=mean(speed))
## # A tibble: 2 × 2
##   violation     p
##   <chr>     <dbl>
## 1 fast       19.9
## 2 slow       11.2
# hflights 패키지
# install.packages("hflights")
library(hflights)

summary(hflights)
##       Year          Month          DayofMonth      DayOfWeek        DepTime    
##  Min.   :2011   Min.   : 1.000   Min.   : 1.00   Min.   :1.000   Min.   :   1  
##  1st Qu.:2011   1st Qu.: 4.000   1st Qu.: 8.00   1st Qu.:2.000   1st Qu.:1021  
##  Median :2011   Median : 7.000   Median :16.00   Median :4.000   Median :1416  
##  Mean   :2011   Mean   : 6.514   Mean   :15.74   Mean   :3.948   Mean   :1396  
##  3rd Qu.:2011   3rd Qu.: 9.000   3rd Qu.:23.00   3rd Qu.:6.000   3rd Qu.:1801  
##  Max.   :2011   Max.   :12.000   Max.   :31.00   Max.   :7.000   Max.   :2400  
##                                                                  NA's   :2905  
##     ArrTime     UniqueCarrier        FlightNum      TailNum         
##  Min.   :   1   Length:227496      Min.   :   1   Length:227496     
##  1st Qu.:1215   Class :character   1st Qu.: 855   Class :character  
##  Median :1617   Mode  :character   Median :1696   Mode  :character  
##  Mean   :1578                      Mean   :1962                     
##  3rd Qu.:1953                      3rd Qu.:2755                     
##  Max.   :2400                      Max.   :7290                     
##  NA's   :3066                                                       
##  ActualElapsedTime    AirTime         ArrDelay          DepDelay      
##  Min.   : 34.0     Min.   : 11.0   Min.   :-70.000   Min.   :-33.000  
##  1st Qu.: 77.0     1st Qu.: 58.0   1st Qu.: -8.000   1st Qu.: -3.000  
##  Median :128.0     Median :107.0   Median :  0.000   Median :  0.000  
##  Mean   :129.3     Mean   :108.1   Mean   :  7.094   Mean   :  9.445  
##  3rd Qu.:165.0     3rd Qu.:141.0   3rd Qu.: 11.000   3rd Qu.:  9.000  
##  Max.   :575.0     Max.   :549.0   Max.   :978.000   Max.   :981.000  
##  NA's   :3622      NA's   :3622    NA's   :3622      NA's   :2905     
##     Origin              Dest              Distance          TaxiIn       
##  Length:227496      Length:227496      Min.   :  79.0   Min.   :  1.000  
##  Class :character   Class :character   1st Qu.: 376.0   1st Qu.:  4.000  
##  Mode  :character   Mode  :character   Median : 809.0   Median :  5.000  
##                                        Mean   : 787.8   Mean   :  6.099  
##                                        3rd Qu.:1042.0   3rd Qu.:  7.000  
##                                        Max.   :3904.0   Max.   :165.000  
##                                                         NA's   :3066     
##     TaxiOut         Cancelled       CancellationCode      Diverted       
##  Min.   :  1.00   Min.   :0.00000   Length:227496      Min.   :0.000000  
##  1st Qu.: 10.00   1st Qu.:0.00000   Class :character   1st Qu.:0.000000  
##  Median : 14.00   Median :0.00000   Mode  :character   Median :0.000000  
##  Mean   : 15.09   Mean   :0.01307                      Mean   :0.002853  
##  3rd Qu.: 18.00   3rd Qu.:0.00000                      3rd Qu.:0.000000  
##  Max.   :163.00   Max.   :1.00000                      Max.   :1.000000  
##  NA's   :2947
glimpse(hflights)
## Rows: 227,496
## Columns: 21
## $ Year              <int> 2011, 2011, 2011, 2011, 2011, 2011, 2011, 2011, 2011…
## $ Month             <int> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1…
## $ DayofMonth        <int> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1…
## $ DayOfWeek         <int> 6, 7, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7, 1, 2…
## $ DepTime           <int> 1400, 1401, 1352, 1403, 1405, 1359, 1359, 1355, 1443…
## $ ArrTime           <int> 1500, 1501, 1502, 1513, 1507, 1503, 1509, 1454, 1554…
## $ UniqueCarrier     <chr> "AA", "AA", "AA", "AA", "AA", "AA", "AA", "AA", "AA"…
## $ FlightNum         <int> 428, 428, 428, 428, 428, 428, 428, 428, 428, 428, 42…
## $ TailNum           <chr> "N576AA", "N557AA", "N541AA", "N403AA", "N492AA", "N…
## $ ActualElapsedTime <int> 60, 60, 70, 70, 62, 64, 70, 59, 71, 70, 70, 56, 63, …
## $ AirTime           <int> 40, 45, 48, 39, 44, 45, 43, 40, 41, 45, 42, 41, 44, …
## $ ArrDelay          <int> -10, -9, -8, 3, -3, -7, -1, -16, 44, 43, 29, 5, -9, …
## $ DepDelay          <int> 0, 1, -8, 3, 5, -1, -1, -5, 43, 43, 29, 19, -2, -3, …
## $ Origin            <chr> "IAH", "IAH", "IAH", "IAH", "IAH", "IAH", "IAH", "IA…
## $ Dest              <chr> "DFW", "DFW", "DFW", "DFW", "DFW", "DFW", "DFW", "DF…
## $ Distance          <int> 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 22…
## $ TaxiIn            <int> 7, 6, 5, 9, 9, 6, 12, 7, 8, 6, 8, 4, 6, 5, 6, 12, 8,…
## $ TaxiOut           <int> 13, 9, 17, 22, 9, 13, 15, 12, 22, 19, 20, 11, 13, 15…
## $ Cancelled         <int> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0…
## $ CancellationCode  <chr> "", "", "", "", "", "", "", "", "", "", "", "", "", …
## $ Diverted          <int> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0…
#이런 데이터 큰 거 아님. 금방 올림
# Month 빈도분석
hflights %>% count(Month)
##    Month     n
## 1      1 18910
## 2      2 17128
## 3      3 19470
## 4      4 18593
## 5      5 19172
## 6      6 19600
## 7      7 20548
## 8      8 20176
## 9      9 18065
## 10    10 18696
## 11    11 18021
## 12    12 19117
# Month가 2월 8월 데이터 추출
hflights %>% filter(Month==2|Month==8) %>%dim()
## [1] 37304    21
#Dest 도착지점(공항명)
glimpse(hflights)
## Rows: 227,496
## Columns: 21
## $ Year              <int> 2011, 2011, 2011, 2011, 2011, 2011, 2011, 2011, 2011…
## $ Month             <int> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1…
## $ DayofMonth        <int> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1…
## $ DayOfWeek         <int> 6, 7, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7, 1, 2…
## $ DepTime           <int> 1400, 1401, 1352, 1403, 1405, 1359, 1359, 1355, 1443…
## $ ArrTime           <int> 1500, 1501, 1502, 1513, 1507, 1503, 1509, 1454, 1554…
## $ UniqueCarrier     <chr> "AA", "AA", "AA", "AA", "AA", "AA", "AA", "AA", "AA"…
## $ FlightNum         <int> 428, 428, 428, 428, 428, 428, 428, 428, 428, 428, 42…
## $ TailNum           <chr> "N576AA", "N557AA", "N541AA", "N403AA", "N492AA", "N…
## $ ActualElapsedTime <int> 60, 60, 70, 70, 62, 64, 70, 59, 71, 70, 70, 56, 63, …
## $ AirTime           <int> 40, 45, 48, 39, 44, 45, 43, 40, 41, 45, 42, 41, 44, …
## $ ArrDelay          <int> -10, -9, -8, 3, -3, -7, -1, -16, 44, 43, 29, 5, -9, …
## $ DepDelay          <int> 0, 1, -8, 3, 5, -1, -1, -5, 43, 43, 29, 19, -2, -3, …
## $ Origin            <chr> "IAH", "IAH", "IAH", "IAH", "IAH", "IAH", "IAH", "IA…
## $ Dest              <chr> "DFW", "DFW", "DFW", "DFW", "DFW", "DFW", "DFW", "DF…
## $ Distance          <int> 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 22…
## $ TaxiIn            <int> 7, 6, 5, 9, 9, 6, 12, 7, 8, 6, 8, 4, 6, 5, 6, 12, 8,…
## $ TaxiOut           <int> 13, 9, 17, 22, 9, 13, 15, 12, 22, 19, 20, 11, 13, 15…
## $ Cancelled         <int> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0…
## $ CancellationCode  <chr> "", "", "", "", "", "", "", "", "", "", "", "", "", …
## $ Diverted          <int> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0…
hflights %>% count(Dest)
##     Dest    n
## 1    ABQ 2812
## 2    AEX  724
## 3    AGS    1
## 4    AMA 1297
## 5    ANC  125
## 6    ASE  125
## 7    ATL 7886
## 8    AUS 5022
## 9    AVL  350
## 10   BFL  504
## 11   BHM 2736
## 12   BKG  110
## 13   BNA 3481
## 14   BOS 1752
## 15   BPT    3
## 16   BRO 1692
## 17   BTR 1762
## 18   BWI 2551
## 19   CAE  561
## 20   CHS 1200
## 21   CID  410
## 22   CLE 2140
## 23   CLT 4735
## 24   CMH 1348
## 25   COS 1657
## 26   CRP 4813
## 27   CRW  357
## 28   CVG 1535
## 29   DAL 9820
## 30   DAY  451
## 31   DCA 2699
## 32   DEN 5920
## 33   DFW 6653
## 34   DSM  647
## 35   DTW 2601
## 36   ECP  729
## 37   EGE  110
## 38   ELP 3036
## 39   EWR 4314
## 40   FLL 2462
## 41   GJT  403
## 42   GPT 1618
## 43   GRK   42
## 44   GRR  677
## 45   GSO  630
## 46   GSP 1123
## 47   GUC   86
## 48   HDN  110
## 49   HNL  402
## 50   HOB  309
## 51   HRL 3983
## 52   HSV  923
## 53   IAD 1980
## 54   ICT 1517
## 55   IND 1750
## 56   JAN 2011
## 57   JAX 2135
## 58   JFK  695
## 59   LAS 4082
## 60   LAX 6064
## 61   LBB 1333
## 62   LCH  364
## 63   LEX  584
## 64   LFT 2313
## 65   LGA 2730
## 66   LIT 1579
## 67   LRD 1188
## 68   MAF 2306
## 69   MCI 3174
## 70   MCO 3687
## 71   MDW 2094
## 72   MEM 2399
## 73   MFE 1128
## 74   MIA 2463
## 75   MKE 1588
## 76   MLU  292
## 77   MOB 1674
## 78   MSP 2010
## 79   MSY 6823
## 80   MTJ  164
## 81   OAK  690
## 82   OKC 3170
## 83   OMA 2044
## 84   ONT  952
## 85   ORD 5748
## 86   ORF  717
## 87   PBI 1253
## 88   PDX 1235
## 89   PHL 2367
## 90   PHX 5096
## 91   PIT 1664
## 92   PNS 1539
## 93   PSP  106
## 94   RDU 1740
## 95   RIC  900
## 96   RNO  243
## 97   RSW  948
## 98   SAN 2936
## 99   SAT 4893
## 100  SAV  863
## 101  SDF 1279
## 102  SEA 2615
## 103  SFO 2818
## 104  SHV  787
## 105  SJC  885
## 106  SJU  391
## 107  SLC 2033
## 108  SMF 1014
## 109  SNA 1661
## 110  STL 2509
## 111  TPA 3085
## 112  TUL 2924
## 113  TUS 1565
## 114  TYS 1210
## 115  VPS  880
## 116  XNA 1172
hflights %>% count(Dest) %>% arrange(n)
##     Dest    n
## 1    AGS    1
## 2    BPT    3
## 3    GRK   42
## 4    GUC   86
## 5    PSP  106
## 6    BKG  110
## 7    EGE  110
## 8    HDN  110
## 9    ANC  125
## 10   ASE  125
## 11   MTJ  164
## 12   RNO  243
## 13   MLU  292
## 14   HOB  309
## 15   AVL  350
## 16   CRW  357
## 17   LCH  364
## 18   SJU  391
## 19   HNL  402
## 20   GJT  403
## 21   CID  410
## 22   DAY  451
## 23   BFL  504
## 24   CAE  561
## 25   LEX  584
## 26   GSO  630
## 27   DSM  647
## 28   GRR  677
## 29   OAK  690
## 30   JFK  695
## 31   ORF  717
## 32   AEX  724
## 33   ECP  729
## 34   SHV  787
## 35   SAV  863
## 36   VPS  880
## 37   SJC  885
## 38   RIC  900
## 39   HSV  923
## 40   RSW  948
## 41   ONT  952
## 42   SMF 1014
## 43   GSP 1123
## 44   MFE 1128
## 45   XNA 1172
## 46   LRD 1188
## 47   CHS 1200
## 48   TYS 1210
## 49   PDX 1235
## 50   PBI 1253
## 51   SDF 1279
## 52   AMA 1297
## 53   LBB 1333
## 54   CMH 1348
## 55   ICT 1517
## 56   CVG 1535
## 57   PNS 1539
## 58   TUS 1565
## 59   LIT 1579
## 60   MKE 1588
## 61   GPT 1618
## 62   COS 1657
## 63   SNA 1661
## 64   PIT 1664
## 65   MOB 1674
## 66   BRO 1692
## 67   RDU 1740
## 68   IND 1750
## 69   BOS 1752
## 70   BTR 1762
## 71   IAD 1980
## 72   MSP 2010
## 73   JAN 2011
## 74   SLC 2033
## 75   OMA 2044
## 76   MDW 2094
## 77   JAX 2135
## 78   CLE 2140
## 79   MAF 2306
## 80   LFT 2313
## 81   PHL 2367
## 82   MEM 2399
## 83   FLL 2462
## 84   MIA 2463
## 85   STL 2509
## 86   BWI 2551
## 87   DTW 2601
## 88   SEA 2615
## 89   DCA 2699
## 90   LGA 2730
## 91   BHM 2736
## 92   ABQ 2812
## 93   SFO 2818
## 94   TUL 2924
## 95   SAN 2936
## 96   ELP 3036
## 97   TPA 3085
## 98   OKC 3170
## 99   MCI 3174
## 100  BNA 3481
## 101  MCO 3687
## 102  HRL 3983
## 103  LAS 4082
## 104  EWR 4314
## 105  CLT 4735
## 106  CRP 4813
## 107  SAT 4893
## 108  AUS 5022
## 109  PHX 5096
## 110  ORD 5748
## 111  DEN 5920
## 112  LAX 6064
## 113  DFW 6653
## 114  MSY 6823
## 115  ATL 7886
## 116  DAL 9820
hflights %>% count(Dest) %>% arrange(desc(n))
##     Dest    n
## 1    DAL 9820
## 2    ATL 7886
## 3    MSY 6823
## 4    DFW 6653
## 5    LAX 6064
## 6    DEN 5920
## 7    ORD 5748
## 8    PHX 5096
## 9    AUS 5022
## 10   SAT 4893
## 11   CRP 4813
## 12   CLT 4735
## 13   EWR 4314
## 14   LAS 4082
## 15   HRL 3983
## 16   MCO 3687
## 17   BNA 3481
## 18   MCI 3174
## 19   OKC 3170
## 20   TPA 3085
## 21   ELP 3036
## 22   SAN 2936
## 23   TUL 2924
## 24   SFO 2818
## 25   ABQ 2812
## 26   BHM 2736
## 27   LGA 2730
## 28   DCA 2699
## 29   SEA 2615
## 30   DTW 2601
## 31   BWI 2551
## 32   STL 2509
## 33   MIA 2463
## 34   FLL 2462
## 35   MEM 2399
## 36   PHL 2367
## 37   LFT 2313
## 38   MAF 2306
## 39   CLE 2140
## 40   JAX 2135
## 41   MDW 2094
## 42   OMA 2044
## 43   SLC 2033
## 44   JAN 2011
## 45   MSP 2010
## 46   IAD 1980
## 47   BTR 1762
## 48   BOS 1752
## 49   IND 1750
## 50   RDU 1740
## 51   BRO 1692
## 52   MOB 1674
## 53   PIT 1664
## 54   SNA 1661
## 55   COS 1657
## 56   GPT 1618
## 57   MKE 1588
## 58   LIT 1579
## 59   TUS 1565
## 60   PNS 1539
## 61   CVG 1535
## 62   ICT 1517
## 63   CMH 1348
## 64   LBB 1333
## 65   AMA 1297
## 66   SDF 1279
## 67   PBI 1253
## 68   PDX 1235
## 69   TYS 1210
## 70   CHS 1200
## 71   LRD 1188
## 72   XNA 1172
## 73   MFE 1128
## 74   GSP 1123
## 75   SMF 1014
## 76   ONT  952
## 77   RSW  948
## 78   HSV  923
## 79   RIC  900
## 80   SJC  885
## 81   VPS  880
## 82   SAV  863
## 83   SHV  787
## 84   ECP  729
## 85   AEX  724
## 86   ORF  717
## 87   JFK  695
## 88   OAK  690
## 89   GRR  677
## 90   DSM  647
## 91   GSO  630
## 92   LEX  584
## 93   CAE  561
## 94   BFL  504
## 95   DAY  451
## 96   CID  410
## 97   GJT  403
## 98   HNL  402
## 99   SJU  391
## 100  LCH  364
## 101  CRW  357
## 102  AVL  350
## 103  HOB  309
## 104  MLU  292
## 105  RNO  243
## 106  MTJ  164
## 107  ANC  125
## 108  ASE  125
## 109  BKG  110
## 110  EGE  110
## 111  HDN  110
## 112  PSP  106
## 113  GUC   86
## 114  GRK   42
## 115  BPT    3
## 116  AGS    1
#습관적으로 범주형 데이터는 count로 확인해봐야해. 습관


summary(gapminder)
##         country        continent        year         lifeExp     
##  Afghanistan:  12   Africa  :624   Min.   :1952   Min.   :23.60  
##  Albania    :  12   Americas:300   1st Qu.:1966   1st Qu.:48.20  
##  Algeria    :  12   Asia    :396   Median :1980   Median :60.71  
##  Angola     :  12   Europe  :360   Mean   :1980   Mean   :59.47  
##  Argentina  :  12   Oceania : 24   3rd Qu.:1993   3rd Qu.:70.85  
##  Australia  :  12                  Max.   :2007   Max.   :82.60  
##  (Other)    :1632                                                
##       pop              gdpPercap       
##  Min.   :6.001e+04   Min.   :   241.2  
##  1st Qu.:2.794e+06   1st Qu.:  1202.1  
##  Median :7.024e+06   Median :  3531.8  
##  Mean   :2.960e+07   Mean   :  7215.3  
##  3rd Qu.:1.959e+07   3rd Qu.:  9325.5  
##  Max.   :1.319e+09   Max.   :113523.1  
## 
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(continent)
## # A tibble: 5 × 2
##   continent     n
##   <fct>     <int>
## 1 Africa      624
## 2 Americas    300
## 3 Asia        396
## 4 Europe      360
## 5 Oceania      24
#대륙별 기대수명
gapminder %>% group_by(continent) %>% summarise(m=mean(lifeExp)) %>% arrange()
## # A tibble: 5 × 2
##   continent     m
##   <fct>     <dbl>
## 1 Africa     48.9
## 2 Americas   64.7
## 3 Asia       60.1
## 4 Europe     71.9
## 5 Oceania    74.3
#오름차순,내림차순
gapminder %>% group_by(continent) %>% summarise(m=mean(lifeExp)) %>% arrange(desc(m))
## # A tibble: 5 × 2
##   continent     m
##   <fct>     <dbl>
## 1 Oceania    74.3
## 2 Europe     71.9
## 3 Americas   64.7
## 4 Asia       60.1
## 5 Africa     48.9
# 교안에 없음, 웹페이지에서 데이터 가져와서 tips에 저장
tips<-read.csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/tips.csv')
glimpse(tips)
## Rows: 244
## Columns: 7
## $ total_bill <dbl> 16.99, 10.34, 21.01, 23.68, 24.59, 25.29, 8.77, 26.88, 15.0…
## $ tip        <dbl> 1.01, 1.66, 3.50, 3.31, 3.61, 4.71, 2.00, 3.12, 1.96, 3.23,…
## $ sex        <chr> "Female", "Male", "Male", "Male", "Female", "Male", "Male",…
## $ smoker     <chr> "No", "No", "No", "No", "No", "No", "No", "No", "No", "No",…
## $ day        <chr> "Sun", "Sun", "Sun", "Sun", "Sun", "Sun", "Sun", "Sun", "Su…
## $ time       <chr> "Dinner", "Dinner", "Dinner", "Dinner", "Dinner", "Dinner",…
## $ size       <int> 2, 3, 3, 2, 4, 4, 2, 4, 2, 2, 2, 4, 2, 4, 2, 2, 3, 3, 3, 3,…
#계산서 금액 : total_bill
#요일 : day
#팁 액수(tip)
#시간 : time
#계산한 사람의 성별(sex)
#동석자 수(size)
#흡연한 사람의 여부(smoker)

summary(tips) #어떤 형태인지, 결측지 없는지 본다. 없네
##    total_bill         tip             sex               smoker         
##  Min.   : 3.07   Min.   : 1.000   Length:244         Length:244        
##  1st Qu.:13.35   1st Qu.: 2.000   Class :character   Class :character  
##  Median :17.80   Median : 2.900   Mode  :character   Mode  :character  
##  Mean   :19.79   Mean   : 2.998                                        
##  3rd Qu.:24.13   3rd Qu.: 3.562                                        
##  Max.   :50.81   Max.   :10.000                                        
##      day                time                size     
##  Length:244         Length:244         Min.   :1.00  
##  Class :character   Class :character   1st Qu.:2.00  
##  Mode  :character   Mode  :character   Median :2.00  
##                                        Mean   :2.57  
##                                        3rd Qu.:3.00  
##                                        Max.   :6.00
tips %>% ggplot(aes(size))+geom_histogram()
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

tips %>% ggplot(aes(total_bill,tip))+geom_point()

tips %>% ggplot(aes(total_bill,tip))+geom_point(aes(col=day,pch=sex),size=3)

## 단순하게 데이터를 시각화했지만, 강사님은 이걸 데이터 기반 행정 이라고 합니다
## 수업을 사장이 와서 듣는 기업이 있어. 근본적으로 변화하겠다는 것
## 대부분 수업은 챗지피티 병행. 병행하면 완전 무적입니다.
## chat-gpt 는 다이아몬드 갭마인더 데이터 다 알고 있어. 다 시켜서 데이터만 바꿔

summary(gapminder)
##         country        continent        year         lifeExp     
##  Afghanistan:  12   Africa  :624   Min.   :1952   Min.   :23.60  
##  Albania    :  12   Americas:300   1st Qu.:1966   1st Qu.:48.20  
##  Algeria    :  12   Asia    :396   Median :1980   Median :60.71  
##  Angola     :  12   Europe  :360   Mean   :1980   Mean   :59.47  
##  Argentina  :  12   Oceania : 24   3rd Qu.:1993   3rd Qu.:70.85  
##  Australia  :  12                  Max.   :2007   Max.   :82.60  
##  (Other)    :1632                                                
##       pop              gdpPercap       
##  Min.   :6.001e+04   Min.   :   241.2  
##  1st Qu.:2.794e+06   1st Qu.:  1202.1  
##  Median :7.024e+06   Median :  3531.8  
##  Mean   :2.960e+07   Mean   :  7215.3  
##  3rd Qu.:1.959e+07   3rd Qu.:  9325.5  
##  Max.   :1.319e+09   Max.   :113523.1  
## 
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 %>% ggplot(aes(x=year, y=lifeExp, col=continent))+
  geom_point(alpha=0.2)+geom_smooth()
## `geom_smooth()` using method = 'loess' and formula = 'y ~ x'

x<-gapminder %>% filter(year==1952)
hist(x$lifeExp,main="Histogram of lifeExp in 1952")

x %>% ggplot(aes(continent,lifeExp))+geom_boxplot()

#상자그림,퍼져있는 정도를 나타내, 점은 이상치
# 결재하는 사람이 알고 있지 못하면 보고해봤자 필요 없어.
#따라서 전체 조직의 변화가 필요합니다.
summary(x)
##         country       continent       year         lifeExp     
##  Afghanistan:  1   Africa  :52   Min.   :1952   Min.   :28.80  
##  Albania    :  1   Americas:25   1st Qu.:1952   1st Qu.:39.06  
##  Algeria    :  1   Asia    :33   Median :1952   Median :45.14  
##  Angola     :  1   Europe  :30   Mean   :1952   Mean   :49.06  
##  Argentina  :  1   Oceania : 2   3rd Qu.:1952   3rd Qu.:59.77  
##  Australia  :  1                 Max.   :1952   Max.   :72.67  
##  (Other)    :136                                               
##       pop              gdpPercap       
##  Min.   :    60011   Min.   :   298.9  
##  1st Qu.:  1452026   1st Qu.:   864.8  
##  Median :  3943953   Median :  1968.5  
##  Mean   : 16950402   Mean   :  3725.3  
##  3rd Qu.:  9168198   3rd Qu.:  3913.5  
##  Max.   :556263527   Max.   :108382.4  
## 
## chatGPT chickwt data boxplot in r 로 구현해주세요, 나온 소스 바로 사용
## thingking diagram 에 대한 시각화 도구를 알고 있으면 챗지피티에 알려달래면돼


## 회귀모형, 분류모형 나눠서 진행
## 과적합되지 않게 복잡도를 낮춰서 일반화 범용성을 갖추도록 조정 필요


#회귀분석 검증
data(cars)
library(dplyr)
glimpse(cars)
## Rows: 50
## Columns: 2
## $ speed <dbl> 4, 4, 7, 7, 8, 9, 10, 10, 10, 11, 11, 12, 12, 12, 12, 13, 13, 13…
## $ dist  <dbl> 2, 10, 4, 22, 16, 10, 18, 26, 34, 17, 28, 14, 20, 24, 28, 26, 34…
plot(cars)
car_model<-lm(dist~speed,data=cars)
glimpse(car_model)
## List of 12
##  $ coefficients : Named num [1:2] -17.58 3.93
##   ..- attr(*, "names")= chr [1:2] "(Intercept)" "speed"
##  $ residuals    : Named num [1:50] 3.85 11.85 -5.95 12.05 2.12 ...
##   ..- attr(*, "names")= chr [1:50] "1" "2" "3" "4" ...
##  $ effects      : Named num [1:50] -303.914 145.552 -8.115 9.885 0.194 ...
##   ..- attr(*, "names")= chr [1:50] "(Intercept)" "speed" "" "" ...
##  $ rank         : int 2
##  $ fitted.values: Named num [1:50] -1.85 -1.85 9.95 9.95 13.88 ...
##   ..- attr(*, "names")= chr [1:50] "1" "2" "3" "4" ...
##  $ assign       : int [1:2] 0 1
##  $ qr           :List of 5
##   ..$ qr   : num [1:50, 1:2] -7.071 0.141 0.141 0.141 0.141 ...
##   .. ..- attr(*, "dimnames")=List of 2
##   .. ..- attr(*, "assign")= int [1:2] 0 1
##   ..$ qraux: num [1:2] 1.14 1.27
##   ..$ pivot: int [1:2] 1 2
##   ..$ tol  : num 1e-07
##   ..$ rank : int 2
##   ..- attr(*, "class")= chr "qr"
##  $ df.residual  : int 48
##  $ xlevels      : Named list()
##  $ call         : language lm(formula = dist ~ speed, data = cars)
##  $ terms        :Classes 'terms', 'formula'  language dist ~ speed
##   .. ..- attr(*, "variables")= language list(dist, speed)
##   .. ..- attr(*, "factors")= int [1:2, 1] 0 1
##   .. .. ..- attr(*, "dimnames")=List of 2
##   .. ..- attr(*, "term.labels")= chr "speed"
##   .. ..- attr(*, "order")= int 1
##   .. ..- attr(*, "intercept")= int 1
##   .. ..- attr(*, "response")= int 1
##   .. ..- attr(*, ".Environment")=<environment: R_GlobalEnv> 
##   .. ..- attr(*, "predvars")= language list(dist, speed)
##   .. ..- attr(*, "dataClasses")= Named chr [1:2] "numeric" "numeric"
##   .. .. ..- attr(*, "names")= chr [1:2] "dist" "speed"
##  $ model        :'data.frame':   50 obs. of  2 variables:
##   ..$ dist : num [1:50] 2 10 4 22 16 10 18 26 34 17 ...
##   ..$ speed: num [1:50] 4 4 7 7 8 9 10 10 10 11 ...
##   ..- attr(*, "terms")=Classes 'terms', 'formula'  language dist ~ speed
##   .. .. ..- attr(*, "variables")= language list(dist, speed)
##   .. .. ..- attr(*, "factors")= int [1:2, 1] 0 1
##   .. .. .. ..- attr(*, "dimnames")=List of 2
##   .. .. ..- attr(*, "term.labels")= chr "speed"
##   .. .. ..- attr(*, "order")= int 1
##   .. .. ..- attr(*, "intercept")= int 1
##   .. .. ..- attr(*, "response")= int 1
##   .. .. ..- attr(*, ".Environment")=<environment: R_GlobalEnv> 
##   .. .. ..- attr(*, "predvars")= language list(dist, speed)
##   .. .. ..- attr(*, "dataClasses")= Named chr [1:2] "numeric" "numeric"
##   .. .. .. ..- attr(*, "names")= chr [1:2] "dist" "speed"
##  - attr(*, "class")= chr "lm"
coef(car_model)
## (Intercept)       speed 
##  -17.579095    3.932409
abline(car_model,col='red')

fitted(car_model) #모델값
##         1         2         3         4         5         6         7         8 
## -1.849460 -1.849460  9.947766  9.947766 13.880175 17.812584 21.744993 21.744993 
##         9        10        11        12        13        14        15        16 
## 21.744993 25.677401 25.677401 29.609810 29.609810 29.609810 29.609810 33.542219 
##        17        18        19        20        21        22        23        24 
## 33.542219 33.542219 33.542219 37.474628 37.474628 37.474628 37.474628 41.407036 
##        25        26        27        28        29        30        31        32 
## 41.407036 41.407036 45.339445 45.339445 49.271854 49.271854 49.271854 53.204263 
##        33        34        35        36        37        38        39        40 
## 53.204263 53.204263 53.204263 57.136672 57.136672 57.136672 61.069080 61.069080 
##        41        42        43        44        45        46        47        48 
## 61.069080 61.069080 61.069080 68.933898 72.866307 76.798715 76.798715 76.798715 
##        49        50 
## 76.798715 80.731124
residuals(car_model) #잔차, 오차, 이값이 크면 앉좋아
##          1          2          3          4          5          6          7 
##   3.849460  11.849460  -5.947766  12.052234   2.119825  -7.812584  -3.744993 
##          8          9         10         11         12         13         14 
##   4.255007  12.255007  -8.677401   2.322599 -15.609810  -9.609810  -5.609810 
##         15         16         17         18         19         20         21 
##  -1.609810  -7.542219   0.457781   0.457781  12.457781 -11.474628  -1.474628 
##         22         23         24         25         26         27         28 
##  22.525372  42.525372 -21.407036 -15.407036  12.592964 -13.339445  -5.339445 
##         29         30         31         32         33         34         35 
## -17.271854  -9.271854   0.728146 -11.204263   2.795737  22.795737  30.795737 
##         36         37         38         39         40         41         42 
## -21.136672 -11.136672  10.863328 -29.069080 -13.069080  -9.069080  -5.069080 
##         43         44         45         46         47         48         49 
##   2.930920  -2.933898 -18.866307  -6.798715  15.201285  16.201285  43.201285 
##         50 
##   4.268876
nx1<-data.frame(speed=c(21.5)) #속도 21.5일 때
predict(car_model,nx1)    #제동거리 66.96769 나옴
##        1 
## 66.96769
nx <-data.frame(speed=c(21.5, 25.0, 25.5, 26.0, 26.5, 27.0, 28.0))
plot(nx$speed,predict(car_model,nx),col='red',cex=2,pch=20)
abline(car_model)

##내일 분석기법 중에 random forest, logistic 회귀분석

# install.packages("caret")
# install.packages("mlbench") #잠수함 데이터 sonar
library(caret)
## 필요한 패키지를 로딩중입니다: lattice
library(mlbench)
data(Sonar)
glimpse(Sonar)
## Rows: 208
## Columns: 61
## $ V1    <dbl> 0.0200, 0.0453, 0.0262, 0.0100, 0.0762, 0.0286, 0.0317, 0.0519, …
## $ V2    <dbl> 0.0371, 0.0523, 0.0582, 0.0171, 0.0666, 0.0453, 0.0956, 0.0548, …
## $ V3    <dbl> 0.0428, 0.0843, 0.1099, 0.0623, 0.0481, 0.0277, 0.1321, 0.0842, …
## $ V4    <dbl> 0.0207, 0.0689, 0.1083, 0.0205, 0.0394, 0.0174, 0.1408, 0.0319, …
## $ V5    <dbl> 0.0954, 0.1183, 0.0974, 0.0205, 0.0590, 0.0384, 0.1674, 0.1158, …
## $ V6    <dbl> 0.0986, 0.2583, 0.2280, 0.0368, 0.0649, 0.0990, 0.1710, 0.0922, …
## $ V7    <dbl> 0.1539, 0.2156, 0.2431, 0.1098, 0.1209, 0.1201, 0.0731, 0.1027, …
## $ V8    <dbl> 0.1601, 0.3481, 0.3771, 0.1276, 0.2467, 0.1833, 0.1401, 0.0613, …
## $ V9    <dbl> 0.3109, 0.3337, 0.5598, 0.0598, 0.3564, 0.2105, 0.2083, 0.1465, …
## $ V10   <dbl> 0.2111, 0.2872, 0.6194, 0.1264, 0.4459, 0.3039, 0.3513, 0.2838, …
## $ V11   <dbl> 0.1609, 0.4918, 0.6333, 0.0881, 0.4152, 0.2988, 0.1786, 0.2802, …
## $ V12   <dbl> 0.1582, 0.6552, 0.7060, 0.1992, 0.3952, 0.4250, 0.0658, 0.3086, …
## $ V13   <dbl> 0.2238, 0.6919, 0.5544, 0.0184, 0.4256, 0.6343, 0.0513, 0.2657, …
## $ V14   <dbl> 0.0645, 0.7797, 0.5320, 0.2261, 0.4135, 0.8198, 0.3752, 0.3801, …
## $ V15   <dbl> 0.0660, 0.7464, 0.6479, 0.1729, 0.4528, 1.0000, 0.5419, 0.5626, …
## $ V16   <dbl> 0.2273, 0.9444, 0.6931, 0.2131, 0.5326, 0.9988, 0.5440, 0.4376, …
## $ V17   <dbl> 0.3100, 1.0000, 0.6759, 0.0693, 0.7306, 0.9508, 0.5150, 0.2617, …
## $ V18   <dbl> 0.2999, 0.8874, 0.7551, 0.2281, 0.6193, 0.9025, 0.4262, 0.1199, …
## $ V19   <dbl> 0.5078, 0.8024, 0.8929, 0.4060, 0.2032, 0.7234, 0.2024, 0.6676, …
## $ V20   <dbl> 0.4797, 0.7818, 0.8619, 0.3973, 0.4636, 0.5122, 0.4233, 0.9402, …
## $ V21   <dbl> 0.5783, 0.5212, 0.7974, 0.2741, 0.4148, 0.2074, 0.7723, 0.7832, …
## $ V22   <dbl> 0.5071, 0.4052, 0.6737, 0.3690, 0.4292, 0.3985, 0.9735, 0.5352, …
## $ V23   <dbl> 0.4328, 0.3957, 0.4293, 0.5556, 0.5730, 0.5890, 0.9390, 0.6809, …
## $ V24   <dbl> 0.5550, 0.3914, 0.3648, 0.4846, 0.5399, 0.2872, 0.5559, 0.9174, …
## $ V25   <dbl> 0.6711, 0.3250, 0.5331, 0.3140, 0.3161, 0.2043, 0.5268, 0.7613, …
## $ V26   <dbl> 0.6415, 0.3200, 0.2413, 0.5334, 0.2285, 0.5782, 0.6826, 0.8220, …
## $ V27   <dbl> 0.7104, 0.3271, 0.5070, 0.5256, 0.6995, 0.5389, 0.5713, 0.8872, …
## $ V28   <dbl> 0.8080, 0.2767, 0.8533, 0.2520, 1.0000, 0.3750, 0.5429, 0.6091, …
## $ V29   <dbl> 0.6791, 0.4423, 0.6036, 0.2090, 0.7262, 0.3411, 0.2177, 0.2967, …
## $ V30   <dbl> 0.3857, 0.2028, 0.8514, 0.3559, 0.4724, 0.5067, 0.2149, 0.1103, …
## $ V31   <dbl> 0.1307, 0.3788, 0.8512, 0.6260, 0.5103, 0.5580, 0.5811, 0.1318, …
## $ V32   <dbl> 0.2604, 0.2947, 0.5045, 0.7340, 0.5459, 0.4778, 0.6323, 0.0624, …
## $ V33   <dbl> 0.5121, 0.1984, 0.1862, 0.6120, 0.2881, 0.3299, 0.2965, 0.0990, …
## $ V34   <dbl> 0.7547, 0.2341, 0.2709, 0.3497, 0.0981, 0.2198, 0.1873, 0.4006, …
## $ V35   <dbl> 0.8537, 0.1306, 0.4232, 0.3953, 0.1951, 0.1407, 0.2969, 0.3666, …
## $ V36   <dbl> 0.8507, 0.4182, 0.3043, 0.3012, 0.4181, 0.2856, 0.5163, 0.1050, …
## $ V37   <dbl> 0.6692, 0.3835, 0.6116, 0.5408, 0.4604, 0.3807, 0.6153, 0.1915, …
## $ V38   <dbl> 0.6097, 0.1057, 0.6756, 0.8814, 0.3217, 0.4158, 0.4283, 0.3930, …
## $ V39   <dbl> 0.4943, 0.1840, 0.5375, 0.9857, 0.2828, 0.4054, 0.5479, 0.4288, …
## $ V40   <dbl> 0.2744, 0.1970, 0.4719, 0.9167, 0.2430, 0.3296, 0.6133, 0.2546, …
## $ V41   <dbl> 0.0510, 0.1674, 0.4647, 0.6121, 0.1979, 0.2707, 0.5017, 0.1151, …
## $ V42   <dbl> 0.2834, 0.0583, 0.2587, 0.5006, 0.2444, 0.2650, 0.2377, 0.2196, …
## $ V43   <dbl> 0.2825, 0.1401, 0.2129, 0.3210, 0.1847, 0.0723, 0.1957, 0.1879, …
## $ V44   <dbl> 0.4256, 0.1628, 0.2222, 0.3202, 0.0841, 0.1238, 0.1749, 0.1437, …
## $ V45   <dbl> 0.2641, 0.0621, 0.2111, 0.4295, 0.0692, 0.1192, 0.1304, 0.2146, …
## $ V46   <dbl> 0.1386, 0.0203, 0.0176, 0.3654, 0.0528, 0.1089, 0.0597, 0.2360, …
## $ V47   <dbl> 0.1051, 0.0530, 0.1348, 0.2655, 0.0357, 0.0623, 0.1124, 0.1125, …
## $ V48   <dbl> 0.1343, 0.0742, 0.0744, 0.1576, 0.0085, 0.0494, 0.1047, 0.0254, …
## $ V49   <dbl> 0.0383, 0.0409, 0.0130, 0.0681, 0.0230, 0.0264, 0.0507, 0.0285, …
## $ V50   <dbl> 0.0324, 0.0061, 0.0106, 0.0294, 0.0046, 0.0081, 0.0159, 0.0178, …
## $ V51   <dbl> 0.0232, 0.0125, 0.0033, 0.0241, 0.0156, 0.0104, 0.0195, 0.0052, …
## $ V52   <dbl> 0.0027, 0.0084, 0.0232, 0.0121, 0.0031, 0.0045, 0.0201, 0.0081, …
## $ V53   <dbl> 0.0065, 0.0089, 0.0166, 0.0036, 0.0054, 0.0014, 0.0248, 0.0120, …
## $ V54   <dbl> 0.0159, 0.0048, 0.0095, 0.0150, 0.0105, 0.0038, 0.0131, 0.0045, …
## $ V55   <dbl> 0.0072, 0.0094, 0.0180, 0.0085, 0.0110, 0.0013, 0.0070, 0.0121, …
## $ V56   <dbl> 0.0167, 0.0191, 0.0244, 0.0073, 0.0015, 0.0089, 0.0138, 0.0097, …
## $ V57   <dbl> 0.0180, 0.0140, 0.0316, 0.0050, 0.0072, 0.0057, 0.0092, 0.0085, …
## $ V58   <dbl> 0.0084, 0.0049, 0.0164, 0.0044, 0.0048, 0.0027, 0.0143, 0.0047, …
## $ V59   <dbl> 0.0090, 0.0052, 0.0095, 0.0040, 0.0107, 0.0051, 0.0036, 0.0048, …
## $ V60   <dbl> 0.0032, 0.0044, 0.0078, 0.0117, 0.0094, 0.0062, 0.0103, 0.0053, …
## $ Class <fct> R, R, R, R, R, R, R, R, R, R, R, R, R, R, R, R, R, R, R, R, R, R…
summary(Sonar)
##        V1                V2                V3                V4         
##  Min.   :0.00150   Min.   :0.00060   Min.   :0.00150   Min.   :0.00580  
##  1st Qu.:0.01335   1st Qu.:0.01645   1st Qu.:0.01895   1st Qu.:0.02438  
##  Median :0.02280   Median :0.03080   Median :0.03430   Median :0.04405  
##  Mean   :0.02916   Mean   :0.03844   Mean   :0.04383   Mean   :0.05389  
##  3rd Qu.:0.03555   3rd Qu.:0.04795   3rd Qu.:0.05795   3rd Qu.:0.06450  
##  Max.   :0.13710   Max.   :0.23390   Max.   :0.30590   Max.   :0.42640  
##        V5                V6                V7               V8         
##  Min.   :0.00670   Min.   :0.01020   Min.   :0.0033   Min.   :0.00550  
##  1st Qu.:0.03805   1st Qu.:0.06703   1st Qu.:0.0809   1st Qu.:0.08042  
##  Median :0.06250   Median :0.09215   Median :0.1070   Median :0.11210  
##  Mean   :0.07520   Mean   :0.10457   Mean   :0.1217   Mean   :0.13480  
##  3rd Qu.:0.10028   3rd Qu.:0.13412   3rd Qu.:0.1540   3rd Qu.:0.16960  
##  Max.   :0.40100   Max.   :0.38230   Max.   :0.3729   Max.   :0.45900  
##        V9               V10              V11              V12        
##  Min.   :0.00750   Min.   :0.0113   Min.   :0.0289   Min.   :0.0236  
##  1st Qu.:0.09703   1st Qu.:0.1113   1st Qu.:0.1293   1st Qu.:0.1335  
##  Median :0.15225   Median :0.1824   Median :0.2248   Median :0.2490  
##  Mean   :0.17800   Mean   :0.2083   Mean   :0.2360   Mean   :0.2502  
##  3rd Qu.:0.23342   3rd Qu.:0.2687   3rd Qu.:0.3016   3rd Qu.:0.3312  
##  Max.   :0.68280   Max.   :0.7106   Max.   :0.7342   Max.   :0.7060  
##       V13              V14              V15              V16        
##  Min.   :0.0184   Min.   :0.0273   Min.   :0.0031   Min.   :0.0162  
##  1st Qu.:0.1661   1st Qu.:0.1752   1st Qu.:0.1646   1st Qu.:0.1963  
##  Median :0.2640   Median :0.2811   Median :0.2817   Median :0.3047  
##  Mean   :0.2733   Mean   :0.2966   Mean   :0.3202   Mean   :0.3785  
##  3rd Qu.:0.3513   3rd Qu.:0.3862   3rd Qu.:0.4529   3rd Qu.:0.5357  
##  Max.   :0.7131   Max.   :0.9970   Max.   :1.0000   Max.   :0.9988  
##       V17              V18              V19              V20        
##  Min.   :0.0349   Min.   :0.0375   Min.   :0.0494   Min.   :0.0656  
##  1st Qu.:0.2059   1st Qu.:0.2421   1st Qu.:0.2991   1st Qu.:0.3506  
##  Median :0.3084   Median :0.3683   Median :0.4350   Median :0.5425  
##  Mean   :0.4160   Mean   :0.4523   Mean   :0.5048   Mean   :0.5630  
##  3rd Qu.:0.6594   3rd Qu.:0.6791   3rd Qu.:0.7314   3rd Qu.:0.8093  
##  Max.   :1.0000   Max.   :1.0000   Max.   :1.0000   Max.   :1.0000  
##       V21              V22              V23              V24        
##  Min.   :0.0512   Min.   :0.0219   Min.   :0.0563   Min.   :0.0239  
##  1st Qu.:0.3997   1st Qu.:0.4069   1st Qu.:0.4502   1st Qu.:0.5407  
##  Median :0.6177   Median :0.6649   Median :0.6997   Median :0.6985  
##  Mean   :0.6091   Mean   :0.6243   Mean   :0.6470   Mean   :0.6727  
##  3rd Qu.:0.8170   3rd Qu.:0.8320   3rd Qu.:0.8486   3rd Qu.:0.8722  
##  Max.   :1.0000   Max.   :1.0000   Max.   :1.0000   Max.   :1.0000  
##       V25              V26              V27              V28        
##  Min.   :0.0240   Min.   :0.0921   Min.   :0.0481   Min.   :0.0284  
##  1st Qu.:0.5258   1st Qu.:0.5442   1st Qu.:0.5319   1st Qu.:0.5348  
##  Median :0.7211   Median :0.7545   Median :0.7456   Median :0.7319  
##  Mean   :0.6754   Mean   :0.6999   Mean   :0.7022   Mean   :0.6940  
##  3rd Qu.:0.8737   3rd Qu.:0.8938   3rd Qu.:0.9171   3rd Qu.:0.9003  
##  Max.   :1.0000   Max.   :1.0000   Max.   :1.0000   Max.   :1.0000  
##       V29              V30              V31              V32        
##  Min.   :0.0144   Min.   :0.0613   Min.   :0.0482   Min.   :0.0404  
##  1st Qu.:0.4637   1st Qu.:0.4114   1st Qu.:0.3456   1st Qu.:0.2814  
##  Median :0.6808   Median :0.6071   Median :0.4904   Median :0.4296  
##  Mean   :0.6421   Mean   :0.5809   Mean   :0.5045   Mean   :0.4390  
##  3rd Qu.:0.8521   3rd Qu.:0.7352   3rd Qu.:0.6420   3rd Qu.:0.5803  
##  Max.   :1.0000   Max.   :1.0000   Max.   :0.9657   Max.   :0.9306  
##       V33              V34              V35              V36        
##  Min.   :0.0477   Min.   :0.0212   Min.   :0.0223   Min.   :0.0080  
##  1st Qu.:0.2579   1st Qu.:0.2176   1st Qu.:0.1794   1st Qu.:0.1543  
##  Median :0.3912   Median :0.3510   Median :0.3127   Median :0.3211  
##  Mean   :0.4172   Mean   :0.4032   Mean   :0.3926   Mean   :0.3848  
##  3rd Qu.:0.5561   3rd Qu.:0.5961   3rd Qu.:0.5934   3rd Qu.:0.5565  
##  Max.   :1.0000   Max.   :0.9647   Max.   :1.0000   Max.   :1.0000  
##       V37              V38              V39              V40        
##  Min.   :0.0351   Min.   :0.0383   Min.   :0.0371   Min.   :0.0117  
##  1st Qu.:0.1601   1st Qu.:0.1743   1st Qu.:0.1740   1st Qu.:0.1865  
##  Median :0.3063   Median :0.3127   Median :0.2835   Median :0.2781  
##  Mean   :0.3638   Mean   :0.3397   Mean   :0.3258   Mean   :0.3112  
##  3rd Qu.:0.5189   3rd Qu.:0.4405   3rd Qu.:0.4349   3rd Qu.:0.4244  
##  Max.   :0.9497   Max.   :1.0000   Max.   :0.9857   Max.   :0.9297  
##       V41              V42              V43              V44        
##  Min.   :0.0360   Min.   :0.0056   Min.   :0.0000   Min.   :0.0000  
##  1st Qu.:0.1631   1st Qu.:0.1589   1st Qu.:0.1552   1st Qu.:0.1269  
##  Median :0.2595   Median :0.2451   Median :0.2225   Median :0.1777  
##  Mean   :0.2893   Mean   :0.2783   Mean   :0.2465   Mean   :0.2141  
##  3rd Qu.:0.3875   3rd Qu.:0.3842   3rd Qu.:0.3245   3rd Qu.:0.2717  
##  Max.   :0.8995   Max.   :0.8246   Max.   :0.7733   Max.   :0.7762  
##       V45               V46               V47               V48         
##  Min.   :0.00000   Min.   :0.00000   Min.   :0.00000   Min.   :0.00000  
##  1st Qu.:0.09448   1st Qu.:0.06855   1st Qu.:0.06425   1st Qu.:0.04512  
##  Median :0.14800   Median :0.12135   Median :0.10165   Median :0.07810  
##  Mean   :0.19723   Mean   :0.16063   Mean   :0.12245   Mean   :0.09142  
##  3rd Qu.:0.23155   3rd Qu.:0.20037   3rd Qu.:0.15443   3rd Qu.:0.12010  
##  Max.   :0.70340   Max.   :0.72920   Max.   :0.55220   Max.   :0.33390  
##       V49               V50               V51                V52          
##  Min.   :0.00000   Min.   :0.00000   Min.   :0.000000   Min.   :0.000800  
##  1st Qu.:0.02635   1st Qu.:0.01155   1st Qu.:0.008425   1st Qu.:0.007275  
##  Median :0.04470   Median :0.01790   Median :0.013900   Median :0.011400  
##  Mean   :0.05193   Mean   :0.02042   Mean   :0.016069   Mean   :0.013420  
##  3rd Qu.:0.06853   3rd Qu.:0.02527   3rd Qu.:0.020825   3rd Qu.:0.016725  
##  Max.   :0.19810   Max.   :0.08250   Max.   :0.100400   Max.   :0.070900  
##       V53                V54                V55               V56          
##  Min.   :0.000500   Min.   :0.001000   Min.   :0.00060   Min.   :0.000400  
##  1st Qu.:0.005075   1st Qu.:0.005375   1st Qu.:0.00415   1st Qu.:0.004400  
##  Median :0.009550   Median :0.009300   Median :0.00750   Median :0.006850  
##  Mean   :0.010709   Mean   :0.010941   Mean   :0.00929   Mean   :0.008222  
##  3rd Qu.:0.014900   3rd Qu.:0.014500   3rd Qu.:0.01210   3rd Qu.:0.010575  
##  Max.   :0.039000   Max.   :0.035200   Max.   :0.04470   Max.   :0.039400  
##       V57               V58                V59                V60          
##  Min.   :0.00030   Min.   :0.000300   Min.   :0.000100   Min.   :0.000600  
##  1st Qu.:0.00370   1st Qu.:0.003600   1st Qu.:0.003675   1st Qu.:0.003100  
##  Median :0.00595   Median :0.005800   Median :0.006400   Median :0.005300  
##  Mean   :0.00782   Mean   :0.007949   Mean   :0.007941   Mean   :0.006507  
##  3rd Qu.:0.01043   3rd Qu.:0.010350   3rd Qu.:0.010325   3rd Qu.:0.008525  
##  Max.   :0.03550   Max.   :0.044000   Max.   :0.036400   Max.   :0.043900  
##  Class  
##  M:111  
##  R: 97  
##         
##         
##         
## 
Sonar %>% count(Class)
##   Class   n
## 1     M 111
## 2     R  97
set.seed(998)
inTraining <- createDataPartition(y=Sonar$Class, p=.75, list=FALSE)
#타겟변수 비율 조정 가능 p값, 암기해야해 책 찾아보면 안돼
training <- Sonar[ inTraining, ]
testing <- Sonar[ -inTraining, ]

NROW(training)
## [1] 157
NROW(testing)
## [1] 51
# gapminder 7:3 비율로 뽑혔는지 확인

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(continent)
## # A tibble: 5 × 2
##   continent     n
##   <fct>     <int>
## 1 Africa      624
## 2 Americas    300
## 3 Asia        396
## 4 Europe      360
## 5 Oceania      24
set.seed(998)
ginTraining <- createDataPartition(y=gapminder$continent, p=0.8, list=FALSE)
gtraining <- gapminder[ ginTraining, ]
gtesting <- gapminder[ -ginTraining, ]

NROW(gtraining)
## [1] 1365
NROW(gtesting)
## [1] 339
# dia"gapminder"# diamonds 8:2 비율로 뽑혔는지 확인
# 요건 못 해봤네

##내일부터 프로젝트 발표할 때 요런 로직 가져가서 할 수 있어. 데이터는 여러분 맘대로

#다이아몬드 데이터로, price 예측하겠어요=> 회귀모형
#다이아몬드 데이터로, cut 예측 => 분류모형
#머신러닝은 두 가지 밖에 없어요. 회귀모형, 분류모형 질적으로 평가모형 달라요
#희귀한 질병 정상 99.9%, 질병 0.1%, 덮어놓고 정상이라 하면 정확도 99.9%


#로지스틱 회귀분석, 타겟변수가 팩터 가능, 분류모형
#사망확률을 %로 제시하게 됩니다. 0.5 넘어가는 순간 사망자로 표시
#타겟변수가 팩터인지, 카테고리 분류, 고민
#실무에서 많이 안 쓰는 이유 , 해석이 어려워, 
#의료에서 많이 쓰여, 질병에 걸릴 확률 몇 % 발병확률 몇 배 높아 등

summary(car_model)
## 
## Call:
## lm(formula = dist ~ speed, data = cars)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -29.069  -9.525  -2.272   9.215  43.201 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept) -17.5791     6.7584  -2.601   0.0123 *  
## speed         3.9324     0.4155   9.464 1.49e-12 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 15.38 on 48 degrees of freedom
## Multiple R-squared:  0.6511, Adjusted R-squared:  0.6438 
## F-statistic: 89.57 on 1 and 48 DF,  p-value: 1.49e-12
#t-value 절대값이 크다는 것은
# Pr 통계적으로 융의하다는 말 => 우연의 일치가 아니라는 거
# Multiple R-squared 결정계수 65.11% 설명하고 있다
# 직선(회귀분석) 과 곡선(로지스틱회귀)는 해석이 달라요

ucla<-read.csv('https://stats.idre.ucla.edu/stat/data/binary.csv')
library(dplyr)
glimpse(ucla)
## Rows: 400
## Columns: 4
## $ admit <int> 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1…
## $ gre   <int> 380, 660, 800, 640, 520, 760, 560, 400, 540, 700, 800, 440, 760,…
## $ gpa   <dbl> 3.61, 3.67, 4.00, 3.19, 2.93, 3.00, 2.98, 3.08, 3.39, 3.92, 4.00…
## $ rank  <int> 3, 3, 1, 4, 4, 2, 1, 2, 3, 2, 4, 1, 1, 2, 1, 3, 4, 3, 2, 1, 3, 2…
ucla$admit <- as.factor(ucla$admit)
m <- glm(admit~., data=ucla, family="binomial")
summary(m)
## 
## Call:
## glm(formula = admit ~ ., family = "binomial", data = ucla)
## 
## Coefficients:
##              Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -3.449548   1.132846  -3.045  0.00233 ** 
## gre          0.002294   0.001092   2.101  0.03564 *  
## gpa          0.777014   0.327484   2.373  0.01766 *  
## rank        -0.560031   0.127137  -4.405 1.06e-05 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 499.98  on 399  degrees of freedom
## Residual deviance: 459.44  on 396  degrees of freedom
## AIC: 467.44
## 
## Number of Fisher Scoring iterations: 4
#해석이 너무 다르다. 그래서 잘 안씀. 우리가 쓰기에 적합

s<-data.frame(gre=c(376),gpa=c(3.6),rank=c(3))
predict(m,newdata = s, type = 'response')
##         1 
## 0.1869631
s<-data.frame(gre=c(376),gpa=c(4.0),rank=c(3))
predict(m,newdata = s, type = 'response')
##         1 
## 0.2388382
#합격을 시키려면 gre 점수를 끌어올릴 수밖에
s<-data.frame(gre=c(500),gpa=c(3.6),rank=c(3))
predict(m,newdata = s, type = 'response')
##         1 
## 0.2340802
#학습할 수 있는 데이터가 많을 수록 아주 정확한 출력값이 나옵니다
#일관성, 신뢰성이 높은 데이터 필요

#내일 할거는 1차시에는 회귀모형을 이해
#오후에는 caret 사용, 학습하는거 random forest
# 사고가 나는거 가장 영향주는거 
# 직무에 있는 데이터 사용하는게 가장 좋아ㅇ


library(caret)
#Overlayed Density Plots
featurePlot(x = iris[,1:4], 
            y = iris$Species,
            plot = "density",
            scales = list(x = list(relation="free"),
                          y= list(relation="free"),
                          adjust=1.5,
                          layout = c(4, 1),
                          auto.key = list(columns = 3)))

#sepal length 로 세가지 품종 구분할 수 없어 겹쳐있어서
#품종 구부할 때 앞에 두 개는 날려버리고, 뒤에 두 개만 사용해
#복잡도를 떨어뜨리는 이유가 이거에요
#random forest 돌리면 앞 두 개는 버려, 복잡도를 낮춰

## 이런 논리적인 알고리즘이 잘 되어 있어. 이젠 직무능력이 필요해
## caret는 대부분 사람들 몰라. 전공자도 몰라. 좋은 기회에요.
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…
summary(iris)            
##   Sepal.Length    Sepal.Width     Petal.Length    Petal.Width   
##  Min.   :4.300   Min.   :2.000   Min.   :1.000   Min.   :0.100  
##  1st Qu.:5.100   1st Qu.:2.800   1st Qu.:1.600   1st Qu.:0.300  
##  Median :5.800   Median :3.000   Median :4.350   Median :1.300  
##  Mean   :5.843   Mean   :3.057   Mean   :3.758   Mean   :1.199  
##  3rd Qu.:6.400   3rd Qu.:3.300   3rd Qu.:5.100   3rd Qu.:1.800  
##  Max.   :7.900   Max.   :4.400   Max.   :6.900   Max.   :2.500  
##        Species  
##  setosa    :50  
##  versicolor:50  
##  virginica :50  
##                 
##                 
##