Preparacion de Librerias

library(readr)
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.3     ✔ purrr     1.0.2
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ ggplot2   3.4.4     ✔ tibble    3.2.1
## ✔ lubridate 1.9.2     ✔ tidyr     1.3.0
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(caret)
## Loading required package: lattice
## 
## Attaching package: 'caret'
## 
## The following object is masked from 'package:purrr':
## 
##     lift
library(class)
library(psych)
## 
## Attaching package: 'psych'
## 
## The following objects are masked from 'package:ggplot2':
## 
##     %+%, alpha
library(rsample)

Importar y Limpiar Datos

lung <- read.csv("/Users/nathaliacarcoba/Downloads/survey lung cancer.csv", stringsAsFactors = T)

head(lung)
##   GENDER AGE SMOKING YELLOW_FINGERS ANXIETY PEER_PRESSURE CHRONIC.DISEASE
## 1      M  69       1              2       2             1               1
## 2      M  74       2              1       1             1               2
## 3      F  59       1              1       1             2               1
## 4      M  63       2              2       2             1               1
## 5      F  63       1              2       1             1               1
## 6      F  75       1              2       1             1               2
##   FATIGUE ALLERGY WHEEZING ALCOHOL.CONSUMING COUGHING SHORTNESS.OF.BREATH
## 1       2       1        2                 2        2                   2
## 2       2       2        1                 1        1                   2
## 3       2       1        2                 1        2                   2
## 4       1       1        1                 2        1                   1
## 5       1       1        2                 1        2                   2
## 6       2       2        2                 1        2                   2
##   SWALLOWING.DIFFICULTY CHEST.PAIN LUNG_CANCER
## 1                     2          2         YES
## 2                     2          2         YES
## 3                     1          2          NO
## 4                     2          2          NO
## 5                     1          1          NO
## 6                     1          1         YES
missing_values <- is.na(lung)
sum_missing_per_column <- colSums(missing_values)
print(sum_missing_per_column)
##                GENDER                   AGE               SMOKING 
##                     0                     0                     0 
##        YELLOW_FINGERS               ANXIETY         PEER_PRESSURE 
##                     0                     0                     0 
##       CHRONIC.DISEASE               FATIGUE               ALLERGY 
##                     0                     0                     0 
##              WHEEZING     ALCOHOL.CONSUMING              COUGHING 
##                     0                     0                     0 
##   SHORTNESS.OF.BREATH SWALLOWING.DIFFICULTY            CHEST.PAIN 
##                     0                     0                     0 
##           LUNG_CANCER 
##                     0
lung$LUNG_CANCER <- ifelse(lung$LUNG_CANCER == "YES", 2, 1)
lung$GENDER <- ifelse(lung$GENDER == "MALE", 2, 1)

#Cambiar 2 por 1, 1 por 0
lung <- apply(lung, 2, function(x) ifelse(x == 1, 0, ifelse(x == 2, 1, x)))

#Convertir a dataframe
lungdf <- as.data.frame(lung)

Regression Logistica Logit

modelo_logit = glm(LUNG_CANCER~.,
                data=lungdf,
                family=binomial(link="logit"))

summary(modelo_logit)
## 
## Call:
## glm(formula = LUNG_CANCER ~ ., family = binomial(link = "logit"), 
##     data = lungdf)
## 
## Coefficients: (1 not defined because of singularities)
##                       Estimate Std. Error z value Pr(>|z|)    
## (Intercept)           -8.57344    2.48473  -3.450 0.000560 ***
## GENDER                      NA         NA      NA       NA    
## AGE                    0.02444    0.03339   0.732 0.464223    
## SMOKING                1.67806    0.68493   2.450 0.014287 *  
## YELLOW_FINGERS         1.46761    0.74012   1.983 0.047375 *  
## ANXIETY                0.73773    0.78062   0.945 0.344632    
## PEER_PRESSURE          1.76197    0.66099   2.666 0.007684 ** 
## CHRONIC.DISEASE        3.16839    0.87324   3.628 0.000285 ***
## FATIGUE                3.11794    0.83424   3.737 0.000186 ***
## ALLERGY                1.78226    0.74386   2.396 0.016577 *  
## WHEEZING               0.88947    0.82426   1.079 0.280539    
## ALCOHOL.CONSUMING      1.20860    0.75349   1.604 0.108714    
## COUGHING               3.21703    1.04819   3.069 0.002147 ** 
## SHORTNESS.OF.BREATH   -0.73405    0.75580  -0.971 0.331437    
## SWALLOWING.DIFFICULTY  3.18989    1.13171   2.819 0.004823 ** 
## CHEST.PAIN             0.41585    0.66151   0.629 0.529589    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 234.299  on 308  degrees of freedom
## Residual deviance:  92.473  on 294  degrees of freedom
## AIC: 122.47
## 
## Number of Fisher Scoring iterations: 8

Regression Logistica Probit

modelo_probit = glm(LUNG_CANCER~.,
                data=lungdf,
                family=binomial(link="probit"))

summary(modelo_probit)
## 
## Call:
## glm(formula = LUNG_CANCER ~ ., family = binomial(link = "probit"), 
##     data = lungdf)
## 
## Coefficients: (1 not defined because of singularities)
##                       Estimate Std. Error z value Pr(>|z|)    
## (Intercept)           -4.71448    1.37232  -3.435 0.000592 ***
## GENDER                      NA         NA      NA       NA    
## AGE                    0.01158    0.01880   0.616 0.537709    
## SMOKING                0.96884    0.37677   2.571 0.010127 *  
## YELLOW_FINGERS         0.84976    0.40180   2.115 0.034442 *  
## ANXIETY                0.43399    0.43251   1.003 0.315662    
## PEER_PRESSURE          1.02141    0.36377   2.808 0.004988 ** 
## CHRONIC.DISEASE        1.79696    0.47670   3.770 0.000164 ***
## FATIGUE                1.76456    0.45002   3.921 8.81e-05 ***
## ALLERGY                0.97830    0.40064   2.442 0.014613 *  
## WHEEZING               0.50850    0.44240   1.149 0.250391    
## ALCOHOL.CONSUMING      0.70847    0.41111   1.723 0.084834 .  
## COUGHING               1.79859    0.56132   3.204 0.001354 ** 
## SHORTNESS.OF.BREATH   -0.41215    0.41040  -1.004 0.315260    
## SWALLOWING.DIFFICULTY  1.74772    0.61518   2.841 0.004498 ** 
## CHEST.PAIN             0.22425    0.35308   0.635 0.525349    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 234.299  on 308  degrees of freedom
## Residual deviance:  91.114  on 294  degrees of freedom
## AIC: 121.11
## 
## Number of Fisher Scoring iterations: 9

#Comparar CIA Con esto podemos ver cual es el mejor modelo para los datos

CIA_Logit = AIC(modelo_logit)
CIA_Probit = AIC(modelo_probit)
CIA_Logit
## [1] 122.4726
CIA_Probit
## [1] 121.1139
column_names <- names(lungdf)

# Print the list of column names
print(column_names)
##  [1] "GENDER"                "AGE"                   "SMOKING"              
##  [4] "YELLOW_FINGERS"        "ANXIETY"               "PEER_PRESSURE"        
##  [7] "CHRONIC.DISEASE"       "FATIGUE"               "ALLERGY"              
## [10] "WHEEZING"              "ALCOHOL.CONSUMING"     "COUGHING"             
## [13] "SHORTNESS.OF.BREATH"   "SWALLOWING.DIFFICULTY" "CHEST.PAIN"           
## [16] "LUNG_CANCER"

Predicciones

log.odds <- predict(modelo_probit, data.frame(GENDER = 1, AGE = 75, SMOKING = 0, YELLOW_FINGERS = 1, ANXIETY = 0, PEER_PRESSURE= 1, CHRONIC.DISEASE=0, FATIGUE = 0, ALLERGY = 1, WHEEZING = 0, ALCOHOL.CONSUMING = 0, COUGHING = 1, SHORTNESS.OF.BREATH = 1, SWALLOWING.DIFFICULTY = 0,  CHEST.PAIN = 1))
## Warning in predict.lm(object, newdata, se.fit, scale = 1, type = if (type == :
## prediction from rank-deficient fit; attr(*, "non-estim") has doubtful cases
Prob1 = pnorm(log.odds)
Prob1
##         1 
## 0.7305249 
## attr(,"non-estim")
## 1 
## 1
#Prob1 = es la probabilidad de que si tenga cancer de pulmon

predict(modelo_probit, data.frame(GENDER = 1, AGE = 45, SMOKING = 1, YELLOW_FINGERS = 1, ANXIETY = 0, PEER_PRESSURE= 0, CHRONIC.DISEASE=0, FATIGUE = 1, ALLERGY = 0, WHEEZING = 0, ALCOHOL.CONSUMING = 0, COUGHING = 1, SHORTNESS.OF.BREATH = 1, SWALLOWING.DIFFICULTY = 0,  CHEST.PAIN = 0), type="response")
## Warning in predict.lm(object, newdata, se.fit, scale = 1, type = if (type == :
## prediction from rank-deficient fit; attr(*, "non-estim") has doubtful cases
##         1 
## 0.7812305 
## attr(,"non-estim")
## 1 
## 1

Interpretacion de Coefficientes

Nos indica la relevancia de cada variable en cuestion al resultado.

Prob1*coef(modelo_probit)
##           (Intercept)                GENDER                   AGE 
##          -3.444047972                    NA           0.008461683 
##               SMOKING        YELLOW_FINGERS               ANXIETY 
##           0.707763298           0.620769311           0.317041322 
##         PEER_PRESSURE       CHRONIC.DISEASE               FATIGUE 
##           0.746168521           1.312725514           1.289056129 
##               ALLERGY              WHEEZING     ALCOHOL.CONSUMING 
##           0.714670130           0.371468309           0.517553339 
##              COUGHING   SHORTNESS.OF.BREATH SWALLOWING.DIFFICULTY 
##           1.313913071          -0.301082429           1.276751726 
##            CHEST.PAIN 
##           0.163818545

Matriz de Confusion

predicciones <- ifelse(test = modelo_probit$fitted.values > 0.5, yes =1, no = 0)
matriz_confusion <- table(predicciones,modelo_probit$model$LUNG_CANCER,dnn = c( "predicciones","observaciones"))
matriz_confusion
##             observaciones
## predicciones   0   1
##            0  28   6
##            1  11 264

Porcentaje de Certeza

(264+28)/(11+6+28+264)*100
## [1] 94.49838