#Activo las librerias
library(ggplot2)
library(readxl)
library(gridExtra)

# Lectura de datos de excel 
Datos_Logistica <- read_excel("Z:/Mi unidad/3_Formación_Académica/13_Postgrados-Universidades/Especialización en estadistica/6-Modelos_de_Regresión/DataSET.xlsx")

# Grafica de cajas y bigotes para ambos niveles de inflación en un mismo plano

ggplot(data = Datos_Logistica, aes(x = factor(`Nivel de Inflacion`), y = TRM, fill = factor(`Nivel de Inflacion`))) +
  geom_boxplot(outlier.shape = NA) +
  geom_jitter(width = 0.1) +
  theme_bw() +
  labs(title = "Cajas de Bigotes para Nivel de Inflación") +
  scale_fill_manual(values = c("lightblue", "lightgreen"), name = "Nivel de Inflación") +
  theme(legend.position = "top")

#Generacion del modelo de regresión logistica

modelo<-glm(`Nivel de Inflacion` ~ TRM, data=Datos_Logistica, family="binomial")
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
summary(modelo)
## 
## Call:
## glm(formula = `Nivel de Inflacion` ~ TRM, family = "binomial", 
##     data = Datos_Logistica)
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)
## (Intercept) -337.37543  233.21577  -1.447    0.148
## TRM            0.08402    0.05813   1.445    0.148
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 71.5289  on 59  degrees of freedom
## Residual deviance:  5.1114  on 58  degrees of freedom
## AIC: 9.1114
## 
## Number of Fisher Scoring iterations: 12
#Graficacion del modelo

plot(`Nivel de Inflacion` ~ TRM, Datos_Logistica, col = "darkblue",
     main = "Modelo regresión logística",
     ylab = "P(Inflacion=1|trm)",
     xlab = "TRM", pch = "I")


# type = "response" devuelve las predicciones en forma de probabilidad en lugar de en log_ODDs
curve(predict(modelo, data.frame(TRM = x), type = "response"),
      col = "firebrick", lwd = 2.5, add = TRUE)