class: center, middle, inverse, title-slide .title[ # STATS101 ] .subtitle[ ## Something More: Dealing with Qualitative Explanatory Variables ] .author[ ### Sanghoon Park ] .date[ ### University of South Carolina ] --- ## Understanding Concepts of Regression ### Simple Regression: Model with a single predictor -- .pull-left[ <img src="fig/w7_fig1.png" width="100%" style="display: block; margin: auto;" /> ] -- .pull-right[ <br><br> + `\(Y\)`: 종속변수 + `\(X_1\)`: 예측변수 + `\(u_x\)`: 예측변수에 영향을 미칠 수 있는 외부의 요인 + `\(u_y\)`: 종속변수에 영향을 미칠 수 있는 외부의 요인 + 관계 양상은 `\(X_1\)`으로부터 `\(Y\)`, 즉, `\(X_1\)`이 `\(Y\)`의 원인 ] --- ## Understanding Concepts of Regression ### Simple Regression: Model with a single predictor -- <img src="fig/w7_fig2.png" width="50%" style="display: block; margin: auto;" /> --- ## Understanding Concepts of Regression ### Simple Regression: Model with a single predictor <img src="fig/w7_fig3.png" width="51%" style="display: block; margin: auto;" /> --- ## Understanding Concepts of Regression ### Simple Regression: Model with a single predictor <img src="fig/w7_fig4.png" width="50%" style="display: block; margin: auto;" /> --- ## Understanding Concepts of Regression ### Simple Regression: Model with a single predictor <img src="fig/w7_fig5.png" width="50%" style="display: block; margin: auto;" /> --- ## Understanding Concepts of Regression ### Multiple Regression: Model with multiple predictors <img src="fig/w7_fig6.png" width="50%" style="display: block; margin: auto;" /> --- ## Understanding Concepts of Regression ### Multiple Regression: Model with multiple predictors <img src="fig/w7_fig7.png" width="50%" style="display: block; margin: auto;" /> --- ## Drawing lines (`geom_smooth`) 앞서 하나의 예측변수와 종속변수 간의 관계를 파악하기 위해서 산포도를 그리고, 그 둘의 관계를 나타내는 경향선(trend line)을 그린 바 있다. -- Q. 왜 경향선을 그리는 것일까? -- A. 경향선은 우리에게 주어진 `\(X\)`의 값에서 `\(Y\)`가 어떤 값을 가지게 될지 추측하는 데 도움을 준다. .pull-left[ + 우리는 `geom_smooth`라는 `{ggplot2}` 패키지의 함수를 이용해서 경향선(혹은 모든 점에 가장 잘 들어맞는 선)을 그릴 수 있다. + 다음은 `geom_smooth`의 옵션 중 `method = "lm"`을 설정한 결과이다. ] .pull-right[ .panelset[ .panel[.panel-name[R-code] ```r # libraries library(tidyverse) library(moderndive) # mtcars ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() + geom_smooth(method = "lm") + theme_bw() ``` ] .panel[.panel-name[Plot] <img src="D3S6_files/figure-html/unnamed-chunk-9-1.png" style="display: block; margin: auto;" /> ] ] ] --- ## Why not just take an average? 앞의 `mtcars` 예제를 생각해보자. -- + 모든 `wt` 값의 평균을 가지고 `mpg`를 예측한다고 해보자. -- 이때의 문제점은 무엇일까? -- + 우리가 가진 데이터의 `\(X\)` 값들만 가지고 정확한 추측을 해야만 한다는 것이다. -- + 하지만 과연 이것이 "정확한 추측"일 수 있을까? -- + 차량 무게(`wt`)에 따라 평균 `mpg` 값을 살펴보자. -- .pull-left[ ```r # manually mtcars |> group_by(wt) |> summarise(ave_mpg = mean(mpg, na.rm = TRUE)) ``` ] .pull-right[ ``` ## # A tibble: 10 × 2 ## wt ave_mpg ## <dbl> <dbl> ## 1 1.51 30.4 ## 2 1.62 30.4 ## 3 1.84 33.9 ## 4 1.94 27.3 ## 5 2.14 26 ## 6 2.2 32.4 ## 7 2.32 22.8 ## 8 2.46 21.5 ## 9 2.62 21 ## 10 2.77 19.7 ``` ] --- ## Regression models (`lm`) ### Continous (number) variables 만약 경향선에서 `\(y\)` 절편이나 기울기에 해당하는 값을 찾고싶다면, `lm()` 함수를 이용하여 회귀모델을 적합할 수 있다. 그리고 `{moderndive}`의 `get_regression_table()` 함수를 이용하여 그 결과를 정리된 표로 얻을 수 있다. .panelset[ .panel[.panel-name[R-code] ```r # lm(Y ~ X, data = DATA) # TEMPLATE weight_m = lm(mpg ~ wt, data = mtcars) get_regression_table(weight_m) ``` ] .panel[.panel-name[Result] ``` ## # A tibble: 2 × 7 ## term estimate std_error statistic p_value lower_ci upper_ci ## <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> ## 1 intercept 37.3 1.88 19.9 0 33.4 41.1 ## 2 wt -5.34 0.559 -9.56 0 -6.49 -4.20 ``` ] ] 물론 `base` 함수의 `summary()`를 이용해도 동일한 결과를 얻을 수 있다. --- ## Recap: Continuous variables 조금 더 이론적으로 살펴보자. -- 예측변수 `\(x\)`가 실수에 해당하는, 연속형 변수라고 하자( `\(x \in \mathbb{R}\)`). -- $$ y = \alpha + \beta x + u. $$ -- 이때, `\(\beta\)`이 의미하는 것은 무엇일까? --- ## Qualitative variables 이번에는 예측변수 `\(w\)`가 연속형이 아니라 서로 배타적인(mutually exclusive) 카테고리로 측정된 분류형 변수라고 고려해보자( `\(w \in \{A, B, C\}\)`). + 이러한 변수를 종종 질적 변수(qualitative variables)라고도 한다. + 혹은 0과 1의 값만 가지는 경우, 다른 정보량을 포함하지 않는다는 의미로 더미변수(dummy variables)라고도 한다. $$ z = \gamma + \delta w + v. $$ 이때, `\(\delta\)`의 의미는 무엇일까? --- ## Qualitative variables 두 모델의 차이는 무엇일까? + 두 모델에서 차이는 예측변수의 유형이 다르다는 것이다. + `\(x \in \mathbb{R}\)` + `\(w \in \{A, B, C\}\)` 그렇다면 대체 `\(w\)`는 `\(x\)`와 어떻게 다를까? + 더미변수 `\(w\)`는 `\(wA\)`, `\(wB\)`, `\(wC\)`의 세 가지 구성변수로 쪼개어 볼 수 있다. $$ `\begin{aligned} w = \begin{cases} A & \text{iff } wA = 1;\\ B & \text{iff } wB = 1;\\ C & \text{iff } wC = 1, \end{cases} \end{aligned}` $$ + 즉, 변수 `\(w\)`는 `\(wA\)`가 1일때 `\(A\)`로 코딩되었으며, `\(wB\)`가 1일 때, `\(B\)`, `\(wC\)`가 1일 때 `\(C\)`로 코딩되었다. 합칠 수도 있고, 쪼갤 수도 있다. --- ## In a regression 만약 `\(w\)`를 세 구성변수로 쪼갤 수 있다면, 우리는 `\(z= \gamma + \delta w + v\)`를 다음과 같이 재구성해볼 수 있을 것이다: $$ `\begin{aligned} z&= \gamma + \delta_1 I(w = A) + \delta_2 I(w=B) + \delta_3 I(w=C) + v\\ z&= \gamma + \delta_1 wA + \delta_2 wB + \delta_3 wC + v. \end{aligned}` $$ 자, 이렇게 바꾸어도 똑같은 결과를 얻을 수 있을까? --- ## In a regression 완전다중공선성(Perfect multicollinearity)의 문제가 존재 $$ wA + wB + wC = 1 $$ + 즉, 세 구성변수를 모두 투입할 경우에 그 변수는 변하지 않는 수, 상수(constant; intercept)가 되어 버린다. + 1로 고정되어버린다는 의미 마찬가지로 "다른 조건이 모두 일정할 때 (*Ceteris paribus*)"라는 조건에도 문제가 생김 $$ z = \gamma + \delta_1 wA + \delta_2 wB + \delta_3 wC + v $$ --- ## In a regression ### Working with dummy variables 더미변수를 가지고 분석할 때는, 더미변수 중 하나를 제외하고 모델에 투입해야 한다. $$ `\begin{aligned} &z = \gamma + \delta_2 wB + \delta_3 wC + v\\ &z = \gamma + \delta_1 wA + \delta_3 wC + v\\ &z = \gamma + \delta_1 wA + \delta_2 wB + v\\ \end{aligned}` $$ 더미 변수의 효과는 항상 생략된 카테고리에 비교하여 해석될 수 있음. --- ## Qualitative variables with **R** 남자 대 여자와 같은 숫자로 되어 있지 않은 변수들을 R에서는 어떻게 다룰 수 있을까? -- + 만약 질적 변수가 분류형으로 코딩되어 있다면? -- + 모델에 투입하면 자동으로 분류 중 하나를 생략하고, 그 생략된 분류를 기준으로 나머지 분류들에 대한 계수값을 추정한다. -- + 만약 분류가 각각 더미 코딩되어 있다면? (e.g. 3개의 분류가 각각 분류1, 분류2, 분류3으로 0, 1을 값으로 갖도록 코딩된 경우) -- + 3개 중 기준으로 삼고 싶은 것 하나를 제외하고 모델에 포함 --- ## Qualitative variables with **R** R로 살펴보자. .panelset[ .panel[.panel-name[R-code] ```r # let's look at rank table(evals$rank) mod_rank = lm(score ~ rank, data = evals) get_regression_table(mod_rank) ``` ] .panel[.panel-name[Results] ``` ## ## teaching tenure track tenured ## 102 108 253 ``` ``` ## # A tibble: 3 × 7 ## term estimate std_error statistic p_value lower_ci upper_ci ## <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> ## 1 intercept 4.28 0.054 79.9 0 4.18 4.39 ## 2 rank: tenure track -0.13 0.075 -1.73 0.084 -0.277 0.017 ## 3 rank: tenured -0.145 0.064 -2.28 0.023 -0.27 -0.02 ``` ] ] -- 앞서 말했듯이, 연속형 변수의 계수를 해석하듯 할 수 없다. + 생략된 `teaching` 카테고리에 비하여 나머지 `track`과 `tenured`의 계수값을 설명해야 한다. + 즉, `teaching` 카테고리에 비해 나머지 카테고리들의 종속변수의 평균값을 보여주는 것이 바로 질적 변수의 계수값이다. --- ## Qualitative variables with **R** .panelset[ .panel[.panel-name[R-code] ```r # take the average score across ranks evals |> group_by(rank) |> summarise(ave_score = mean(score, na.rm = TRUE)) ``` ] .panel[.panel-name[Results] ``` ## # A tibble: 3 × 2 ## rank ave_score ## <fct> <dbl> ## 1 teaching 4.28 ## 2 tenure track 4.15 ## 3 tenured 4.14 ``` ] ] 앞의 질적 변수를 포함한 회귀모델과 여기서의 표가 어떻게 같은지를 살펴보자. + 이 표는 각 `rank`의 카테고리별 `score`의 평균을 보여준다. + 위의 회귀모델에서 절편값이 `teaching`의 평균 스코어와 같다는 것을 확인할 수 있다. + 그리고 `ranktenuretrack`는 `teaching`과 `tenure` 간의 차이, (4.28-0.13 = 4.15)임을 확인할 수 있다. + 마찬가지로 회귀모델의 `ranktenured`는 `teaching`과 `tenured` 간의 차이, (4.28-0.145 = 4.14)라는 것을 확인할 수 있다. --- ## Qualitative variables with **R** 계수값들은 모두 기준이 되는 카테고리에 대한 상대적 차이를 보여준다. + 만약 기준을 바꾸고 싶으면 어떻게 할까? -- + 여기에서 요인 변수(`factor`)가 등장한다. + `lm`에서 기준은 변수의 요인 수준(factor level)에서 가장 낮은 요인으로 자동적으로 선택된다. + 따라서 우리는 `factor()` 함수를 이용해 요인 수준을 바꾸어줌으로써 기준을 바꿀 수 있다. -- .panelset[ .panel[.panel-name[R-code] ```r new_evals = evals |> mutate(rank = factor(rank, levels = c("tenured", "tenure track", "teaching"))) # let's look at rank mod_rank = lm(score ~ rank, data = new_evals) get_regression_table(mod_rank) ``` ] .panel[.panel-name[Results] ``` ## # A tibble: 3 × 7 ## term estimate std_error statistic p_value lower_ci upper_ci ## <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> ## 1 intercept 4.14 0.034 122. 0 4.07 4.21 ## 2 rank: tenure track 0.015 0.062 0.249 0.804 -0.107 0.138 ## 3 rank: teaching 0.145 0.064 2.28 0.023 0.02 0.27 ``` ] ] 새로운 기준이 `tenured`가 된 것을 확인할 수 있다. --- class: center, middle background-image: url(https://raw.githubusercontent.com/pherephobia/usc_logo/main/UofSC_Primary_RGB_G.png) background-size: 300px background-position: 11% 15% # Thanks! ## Please do not hesitate to ask questions. Contacts for Instructor. | Contact | Sanghoon Park | | :-------------: | :----------------------------: | | <svg viewBox="0 0 512 512" style="height:1em;position:relative;display:inline-block;top:.1em;" xmlns="http://www.w3.org/2000/svg"> <path d="M440 6.5L24 246.4c-34.4 19.9-31.1 70.8 5.7 85.9L144 379.6V464c0 46.4 59.2 65.5 86.6 28.6l43.8-59.1 111.9 46.2c5.9 2.4 12.1 3.6 18.3 3.6 8.2 0 16.3-2.1 23.6-6.2 12.8-7.2 21.6-20 23.9-34.5l59.4-387.2c6.1-40.1-36.9-68.8-71.5-48.9zM192 464v-64.6l36.6 15.1L192 464zm212.6-28.7l-153.8-63.5L391 169.5c10.7-15.5-9.5-33.5-23.7-21.2L155.8 332.6 48 288 464 48l-59.4 387.3z"></path></svg> | [sp23@email.sc.edu](sp23@email.sc.edu) | | <svg viewBox="0 0 576 512" style="height:1em;position:relative;display:inline-block;top:.1em;" xmlns="http://www.w3.org/2000/svg"> <path d="M528 32H48C21.5 32 0 53.5 0 80v352c0 26.5 21.5 48 48 48h480c26.5 0 48-21.5 48-48V80c0-26.5-21.5-48-48-48zm0 400H303.2c.9-4.5.8 3.6.8-22.4 0-31.8-30.1-57.6-67.2-57.6-10.8 0-18.7 8-44.8 8-26.9 0-33.4-8-44.8-8-37.1 0-67.2 25.8-67.2 57.6 0 26-.2 17.9.8 22.4H48V144h480v288zm-168-80h112c4.4 0 8-3.6 8-8v-16c0-4.4-3.6-8-8-8H360c-4.4 0-8 3.6-8 8v16c0 4.4 3.6 8 8 8zm0-64h112c4.4 0 8-3.6 8-8v-16c0-4.4-3.6-8-8-8H360c-4.4 0-8 3.6-8 8v16c0 4.4 3.6 8 8 8zm0-64h112c4.4 0 8-3.6 8-8v-16c0-4.4-3.6-8-8-8H360c-4.4 0-8 3.6-8 8v16c0 4.4 3.6 8 8 8zm-168 96c35.3 0 64-28.7 64-64s-28.7-64-64-64-64 28.7-64 64 28.7 64 64 64z"></path></svg> | [sanghoon-park.com/](https://www.sanghoon-park.com/) | | <svg viewBox="0 0 448 512" style="height:1em;position:relative;display:inline-block;top:.1em;" xmlns="http://www.w3.org/2000/svg"> <path d="M128 148v-40c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12h-40c-6.6 0-12-5.4-12-12zm140 12h40c6.6 0 12-5.4 12-12v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12zm-128 96h40c6.6 0 12-5.4 12-12v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12zm128 0h40c6.6 0 12-5.4 12-12v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12zm-76 84v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm76 12h40c6.6 0 12-5.4 12-12v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12zm180 124v36H0v-36c0-6.6 5.4-12 12-12h19.5V24c0-13.3 10.7-24 24-24h337c13.3 0 24 10.7 24 24v440H436c6.6 0 12 5.4 12 12zM79.5 463H192v-67c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v67h112.5V49L80 48l-.5 415z"></path></svg> | #305 Gambrell |