setwd("~/ONLINEDS")
#Cargar los paquetes necesarios 
library(pacman)
## Warning: package 'pacman' was built under R version 3.6.3
p_load(markdown,knitr,dplyr,tidyr, tidyverse, hashmap, lubridate,
       summarytools,ggpubr, kableExtra, reshape2,
       sf, tmap, readr, devtools, plotly, gganimate, gifski)

#Primera parte datos diarios y acumulados

#Leer datos 
datos<- read.csv("Casos_Diarios_Estado_Nacional_Confirmados.csv")
#Casos diarios Sonora
Sonora<- t(datos[datos$nombre=="SONORA" ,])
Sonora <- as.vector(Sonora)
Sonora<-Sonora[4:121]
Sonora <- as.numeric(Sonora)
Sonora <- as.vector(Sonora)
csonora <- cumsum(Sonora)

#Casos diarios Sinaloa
Sinaloa<- t(datos[datos$nombre=="SINALOA" ,])
Sinaloa <- as.vector(Sinaloa)
Sinaloa<-Sinaloa[4:121]
Sinaloa <- as.numeric(Sinaloa)
Sinaloa <- as.vector(Sinaloa)
csinaloa <- cumsum(Sinaloa)
#Fecha
Fecha = seq(from = as.Date("2020-01-05"), to = as.Date("2020-05-01"), by = 'day')

SonSin <-data.frame(Fecha, Sonora, Sinaloa)
cSonSin <-data.frame(Fecha, csonora, csinaloa)

#Graficos de casos diarios confirmados
plot(Sonora)

#Grafica Sonora
ggplot(data = SonSin) +
  ggtitle("Casos diarios COVID-19 en Sonora")+
  geom_line(mapping = aes(x = Fecha, y = Sonora ))

# Sinaloa y Sonora
ggplot(data=cSonSin) +
  geom_line(aes(Fecha, csinaloa, colour = 'Sinaloa')) + 
  geom_line(aes(Fecha, csonora, colour ='Sonora') )+ 
  xlab('Fecha')+
  ylab('Casos Diarios') +
  labs(colour = "Estados")+
  transition_reveal(Fecha)

#numero semilla
set.seed(42)
# Declaramos variable 'temp' como un archivo temporal
temp <- tempfile()
ArchivoZip = "http://187.191.75.115/gobmx/salud/datos_abiertos/datos_abiertos_covid19.zip"
download.file(ArchivoZip, temp)

# Utilizamos la función 'unz' para extraer el archivo CSV y lo asignamos a la variable 'temp'
ArchivoCsv = unz(temp, "200503COVID19MEXICO.csv")

# Introducimos los datos del CSV en la tabla
datos <- read.csv(file=ArchivoCsv, header = TRUE, encoding = "UTF-8")


# Eliminamos la referencia al archivo temporal y eliminamos los archivos
unlink(temp)
remove(ArchivoCsv)
remove(temp)
remove(ArchivoZip)

#Asignamos otra variable a datos
datos2 <- datos
datos2$Num <- 1

#Diccionarios
d_origen <- hashmap(c(1,2,99), c("USMER","Fuera USMER","No especificado"))
d_sector <- hashmap(c(1,2,3,4,5,6,7,8,9,10,11,12,13,99), 
                    c("CRUZ ROJA","DIF","ESTATAL","IMSS","IMSS-BIENESTAR","ISSSTE","MUNICIPAL","PEMEX",
                      "PRIVADA","SEDENA","SEMAR","SSA","UNIVERSITARIO","NO ESPECIFICADO"))
d_sexo <- hashmap(c(1,2,99), c("MUJER","HOMBRE","NO ESPECIFICADO"))
d_tipo <- hashmap(c(1,2,99), c("AMBULATORIO","HOSPITALIZADO","NO ESPECIFICADO"))
d_si_no <- hashmap(c(1,2,97,98,99), c("SI","NO","NO APLICA","SE IGNORA","NO ESPECIFICADO"))
d_nacion <- hashmap(c(1,2,99), c("MEXICANA","EXTRANJERA","NO ESPECIFICADO"))
d_resultado <- hashmap(c("1","2","3"),c("Positivo SARS-CoV-2","No positivo SARS-CoV-2","Resultado pendiente"))
d_entidad <- hashmap(c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,
                       36,97,98,99),
                     c("AGU","BCN","BCS","CAM","COA","COL","CHP","CHH","CMX","DUR","GUA","GRO","HID","JAL",
                       "MEX","MIC","MOR","NAY","NLE","OAX","PUE","QUE","ROO","SLP","SIN","SON","TAB","TAM",
                       "TLA","VER","YUC","ZAC","EUM","N_A","S_I","N_E"))

#municipios
datos2$MUNICIPIO_RES <- paste(sprintf("%02d", datos2$ENTIDAD_RES), sprintf("%03d", datos2$MUNICIPIO_RES))
datos2$MUNICIPIO_RES <- as.factor(gsub("[[:space:]]", "", datos2$MUNICIPIO_RES))

#decodificacion
datos2$ORIGEN <- as.factor(d_origen[[datos2$ORIGEN]])
datos2$SECTOR <- as.factor(d_sector[[datos2$SECTOR]])
datos2$ENTIDAD_UM <- as.factor(d_entidad[[datos2$ENTIDAD_UM]])
datos2$SEXO <- as.factor(d_sexo[[datos2$SEXO]])
datos2$ENTIDAD_NAC <- as.factor(d_entidad[[datos2$ENTIDAD_NAC]])
datos2$ENTIDAD_RES <- as.factor(d_entidad[[datos2$ENTIDAD_RES]])
datos2$TIPO_PACIENTE  <- as.factor(d_tipo[[datos2$TIPO_PACIENTE]])
datos2$INTUBADO <- as.factor(d_si_no[[datos2$INTUBADO]])
datos2$NEUMONIA <- as.factor(d_si_no[[datos2$NEUMONIA]])
datos2$NACIONALIDAD <- as.factor(d_nacion[[datos2$NACIONALIDAD]])
datos2$EMBARAZO <- as.factor(d_si_no[[datos2$EMBARAZO]])
datos2$HABLA_LENGUA_INDIG <- as.factor(d_si_no[[datos2$HABLA_LENGUA_INDIG]])
datos2$DIABETES <- as.factor(d_si_no[[datos2$DIABETES]])
datos2$EPOC <- as.factor(d_si_no[[datos2$EPOC]])
datos2$ASMA <- as.factor(d_si_no[[datos2$ASMA]])
datos2$INMUSUPR <- as.factor(d_si_no[[datos2$INMUSUPR]])
datos2$HIPERTENSION <- as.factor(d_si_no[[datos2$HIPERTENSION]])
datos2$OTRA_COM <- as.factor(d_si_no[[datos2$OTRA_COM]])
datos2$CARDIOVASCULAR <- as.factor(d_si_no[[datos2$CARDIOVASCULAR]])
datos2$OBESIDAD <- as.factor(d_si_no[[datos2$OBESIDAD]])
datos2$RENAL_CRONICA <- as.factor(d_si_no[[datos2$RENAL_CRONICA]])
datos2$TABAQUISMO <- as.factor(d_si_no[[datos2$TABAQUISMO]])
datos2$OTRO_CASO <- as.factor(d_si_no[[datos2$OTRO_CASO]])
datos2$RESULTADO <- as.factor(d_resultado[[datos2$RESULTADO]])
datos2$MIGRANTE <- as.factor(d_si_no[[datos2$MIGRANTE]])
datos2$UCI <- as.factor(d_si_no[[datos2$UCI]])


levels(datos2$PAIS_NACIONALIDAD) <- c(levels(datos2$PAIS_NACIONALIDAD), "Se ignora")
datos2$PAIS_NACIONALIDAD[datos2$PAIS_NACIONALIDAD == 99] <- "Se ignora"
levels(datos2$PAIS_ORIGEN) <- c(levels(datos2$PAIS_ORIGEN), "No aplica")
datos2$PAIS_ORIGEN[datos2$PAIS_ORIGEN == 97] <- "No aplica"

#Formato de Fecha
datos$FECHA_ACTUALIZACION <- ymd(datos$FECHA_ACTUALIZACION)
datos2$FECHA_INGRESO <- ymd(datos2$FECHA_INGRESO)
datos2$FECHA_SINTOMAS <- ymd(datos2$FECHA_SINTOMAS)
datos2$FECHA_DEF <- na_if(datos2$FECHA_DEF,"9999-99-99")
datos2$FECHA_DEF <- ymd(datos2$FECHA_DEF)

write.csv(datos2, file = "tabla_procesada.csv")

#Estadistica descriptiva
#view(dfSummary(datos2))
print(dfSummary(datos2, graph.magnif = 0.75), method = 'render', headings = FALSE)
No Variable Stats / Values Freqs (% of Valid) Graph Valid Missing
1 FECHA_ACTUALIZACION [factor] 1. 2020-05-03
95839(100.0%)
95839 (100%) 0 (0%)
2 ID_REGISTRO [factor] 1. 000024 2. 000038 3. 000047 4. 000097 5. 000098 6. 0000a8 7. 0000b1 8. 0000b8 9. 0000da 10. 000115 [ 95829 others ]
1(0.0%)
1(0.0%)
1(0.0%)
1(0.0%)
1(0.0%)
1(0.0%)
1(0.0%)
1(0.0%)
1(0.0%)
1(0.0%)
95829(100.0%)
95839 (100%) 0 (0%)
3 ORIGEN [factor] 1. Fuera USMER 2. USMER
59179(61.8%)
36660(38.2%)
95839 (100%) 0 (0%)
4 SECTOR [factor] 1. CRUZ ROJA 2. DIF 3. ESTATAL 4. IMSS 5. ISSSTE 6. MUNICIPAL 7. NO ESPECIFICADO 8. PEMEX 9. PRIVADA 10. SEDENA [ 3 others ]
8(0.0%)
11(0.0%)
1323(1.4%)
32198(33.6%)
3381(3.5%)
67(0.1%)
644(0.7%)
730(0.8%)
3729(3.9%)
208(0.2%)
53540(55.9%)
95839 (100%) 0 (0%)
5 ENTIDAD_UM [factor] 1. AGU 2. BCN 3. BCS 4. CAM 5. CHH 6. CHP 7. CMX 8. COA 9. COL 10. DUR [ 22 others ]
2009(2.1%)
3915(4.1%)
1280(1.3%)
487(0.5%)
1526(1.6%)
803(0.8%)
23823(24.9%)
3873(4.0%)
229(0.2%)
846(0.9%)
57048(59.5%)
95839 (100%) 0 (0%)
6 SEXO [factor] 1. HOMBRE 2. MUJER
48720(50.8%)
47119(49.2%)
95839 (100%) 0 (0%)
7 ENTIDAD_NAC [factor] 1. AGU 2. BCN 3. BCS 4. CAM 5. CHH 6. CHP 7. CMX 8. COA 9. COL 10. DUR [ 23 others ]
1686(1.8%)
2205(2.3%)
699(0.7%)
450(0.5%)
1352(1.4%)
1248(1.3%)
21553(22.5%)
3732(3.9%)
234(0.2%)
1140(1.2%)
61540(64.2%)
95839 (100%) 0 (0%)
8 ENTIDAD_RES [factor] 1. AGU 2. BCN 3. BCS 4. CAM 5. CHH 6. CHP 7. CMX 8. COA 9. COL 10. DUR [ 22 others ]
1996(2.1%)
3848(4.0%)
1281(1.3%)
434(0.5%)
1535(1.6%)
825(0.9%)
20470(21.4%)
3913(4.1%)
229(0.2%)
828(0.9%)
60480(63.1%)
95839 (100%) 0 (0%)
9 MUNICIPIO_RES [factor] 1. 01001 2. 01002 3. 01003 4. 01004 5. 01005 6. 01006 7. 01007 8. 01008 9. 01009 10. 01010 [ 1667 others ]
1562(1.6%)
15(0.0%)
66(0.1%)
22(0.0%)
101(0.1%)
53(0.1%)
79(0.1%)
24(0.0%)
21(0.0%)
8(0.0%)
93888(98.0%)
95839 (100%) 0 (0%)
10 TIPO_PACIENTE [factor] 1. AMBULATORIO 2. HOSPITALIZADO
70268(73.3%)
25571(26.7%)
95839 (100%) 0 (0%)
11 FECHA_INGRESO [Date] min : 2020-01-01 med : 2020-04-17 max : 2020-05-03 range : 4m 2d 124 distinct values 95839 (100%) 0 (0%)
12 FECHA_SINTOMAS [Date] min : 2020-01-01 med : 2020-04-14 max : 2020-05-03 range : 4m 2d 124 distinct values 95839 (100%) 0 (0%)
13 FECHA_DEF [Date] min : 2020-01-15 med : 2020-04-18 max : 2020-05-03 range : 3m 18d 54 distinct values 3435 (3.58%) 92404 (96.42%)
14 INTUBADO [factor] 1. NO 2. NO APLICA 3. NO ESPECIFICADO 4. SI
23613(24.6%)
70268(73.3%)
24(0.0%)
1934(2.0%)
95839 (100%) 0 (0%)
15 NEUMONIA [factor] 1. NO 2. NO ESPECIFICADO 3. SI
78203(81.6%)
8(0.0%)
17628(18.4%)
95839 (100%) 0 (0%)
16 EDAD [integer] Mean (sd) : 42.1 (17.3) min < med < max: 0 < 41 < 113 IQR (CV) : 23 (0.4) 104 distinct values 95839 (100%) 0 (0%)
17 NACIONALIDAD [factor] 1. EXTRANJERA 2. MEXICANA
1206(1.3%)
94633(98.7%)
95839 (100%) 0 (0%)
18 EMBARAZO [factor] 1. NO 2. NO APLICA 3. SE IGNORA 4. SI
45909(47.9%)
48720(50.8%)
232(0.2%)
978(1.0%)
95839 (100%) 0 (0%)
19 HABLA_LENGUA_INDIG [factor] 1. NO 2. NO ESPECIFICADO 3. SI
92836(96.9%)
1953(2.0%)
1050(1.1%)
95839 (100%) 0 (0%)
20 DIABETES [factor] 1. NO 2. SE IGNORA 3. SI
82544(86.1%)
417(0.4%)
12878(13.4%)
95839 (100%) 0 (0%)
21 EPOC [factor] 1. NO 2. SE IGNORA 3. SI
92973(97.0%)
404(0.4%)
2462(2.6%)
95839 (100%) 0 (0%)
22 ASMA [factor] 1. NO 2. SE IGNORA 3. SI
91102(95.1%)
409(0.4%)
4328(4.5%)
95839 (100%) 0 (0%)
23 INMUSUPR [factor] 1. NO 2. SE IGNORA 3. SI
93099(97.1%)
426(0.4%)
2314(2.4%)
95839 (100%) 0 (0%)
24 HIPERTENSION [factor] 1. NO 2. SE IGNORA 3. SI
78721(82.1%)
402(0.4%)
16716(17.4%)
95839 (100%) 0 (0%)
25 OTRA_COM [factor] 1. NO 2. SE IGNORA 3. SI
90639(94.6%)
558(0.6%)
4642(4.8%)
95839 (100%) 0 (0%)
26 CARDIOVASCULAR [factor] 1. NO 2. SE IGNORA 3. SI
92437(96.5%)
416(0.4%)
2986(3.1%)
95839 (100%) 0 (0%)
27 OBESIDAD [factor] 1. NO 2. SE IGNORA 3. SI
79852(83.3%)
390(0.4%)
15597(16.3%)
95839 (100%) 0 (0%)
28 RENAL_CRONICA [factor] 1. NO 2. SE IGNORA 3. SI
93146(97.2%)
406(0.4%)
2287(2.4%)
95839 (100%) 0 (0%)
29 TABAQUISMO [factor] 1. NO 2. SE IGNORA 3. SI
86124(89.9%)
404(0.4%)
9311(9.7%)
95839 (100%) 0 (0%)
30 OTRO_CASO [factor] 1. NO 2. NO ESPECIFICADO 3. SI
31255(32.6%)
35495(37.0%)
29089(30.3%)
95839 (100%) 0 (0%)
31 RESULTADO [factor] 1. No positivo SARS-CoV-2 2. Positivo SARS-CoV-2 3. Resultado pendiente
59704(62.3%)
23471(24.5%)
12664(13.2%)
95839 (100%) 0 (0%)
32 MIGRANTE [factor] 1. NO 2. NO ESPECIFICADO 3. SI
279(0.3%)
95365(99.5%)
195(0.2%)
95839 (100%) 0 (0%)
33 PAIS_NACIONALIDAD [factor] 1. Alemania 2. Archipiélago de Svalbard 3. Argelia 4. Argentina 5. Ascensión 6. Australia 7. Austria 8. Belice 9. Bolivia 10. Bosnia y Herzegovina [ 61 others ]
27(0.0%)
1(0.0%)
1(0.0%)
40(0.0%)
1(0.0%)
3(0.0%)
1(0.0%)
7(0.0%)
24(0.0%)
1(0.0%)
95733(99.9%)
95839 (100%) 0 (0%)
34 PAIS_ORIGEN [factor] 1. 99 2. Alemania 3. Belice 4. Bolivia 5. Brasil 6. NANANA 7. Chile 8. China 9. Colombia 10. Costa de Marfil [ 13 others ]
95644(99.8%)
1(0.0%)
7(0.0%)
3(0.0%)
2(0.0%)
67(0.1%)
5(0.0%)
1(0.0%)
17(0.0%)
1(0.0%)
91(0.1%)
95839 (100%) 0 (0%)
35 UCI [factor] 1. NO 2. NO APLICA 3. NO ESPECIFICADO 4. SI
23366(24.4%)
70268(73.3%)
25(0.0%)
2180(2.3%)
95839 (100%) 0 (0%)
36 Num [numeric] 1 distinct value
1:95839(100.0%)
95839 (100%) 0 (0%)

Generated by summarytools 0.9.6 (R version 3.6.0)
2020-05-04

#resumen

tab_resultado <- count(datos2, Resultado = datos2$RESULTADO)
tab_resultado["Porcentaje"] <- round(tab_resultado$n*100 / sum(tab_resultado$n),1)  
kable(tab_resultado, format.args = list(big.mark = ",")) %>%
  kable_styling(bootstrap_options = "striped", full_width = F, position = "center")
Resultado n Porcentaje
No positivo SARS-CoV-2 59,704 62.3
Positivo SARS-CoV-2 23,471 24.5
Resultado pendiente 12,664 13.2
#grafica de pie 

tab_resultado_lab <- paste0(tab_resultado$Resultado, "\n (", tab_resultado$Porcentaje, "%)")
ggpie(tab_resultado, "Porcentaje", label = tab_resultado_lab,
      lab.pos = "in", lab.font = "black", lab.adjust = 0,
      fill = "Resultado", color = "white",
      palette = c("#C1D40E", "#FF9999", "#EAEAEA"))

datos3 <- subset(datos2, RESULTADO == "Positivo SARS-CoV-2")

#casos por fecha

tab_fecha_in <- count(datos3, Fecha = datos3$FECHA_INGRESO)
tab_fecha_in["Acumulado"] <- cumsum(tab_fecha_in$n)

g_sum <- ggbarplot(tab_fecha_in, x = "Fecha", y = "n",
                   fill = "steelblue", color = "black",)
g_acum <- ggline(tab_fecha_in, x = "Fecha", y = "Acumulado",
                 color = "steelblue", point.color = "black", point.size = 0.2) +
  scale_y_continuous(labels=function(x) format(x, big.mark = ",", scientific = FALSE))

ggarrange(g_sum, g_acum, labels = c("A)", "B)"), ncol = 2, nrow = 1)

tab_fecha_in2 <- tab_fecha_in %>% mutate(Dif_dias = difftime(tab_fecha_in$Fecha, lag(tab_fecha_in$Fecha,1)))
tab_fecha_in2$Dif_dias <- replace_na(tab_fecha_in2$Dif_dias,1)
tab_fecha_in2$Dif_dias <- as.integer(tab_fecha_in2$Dif_dias)
tab_fecha_in2["Dias"] <- cumsum(tab_fecha_in2$Dif_dias)

datos_log <- data.frame(Dias = tab_fecha_in2$Dias, Acumulado = tab_fecha_in2$Acumulado)
datos_log <- head(datos_log, nrow(datos_log) - 3)
mod_log <- nls(Acumulado ~ SSlogis(Dias, phi1, phi2, phi3), data = datos_log)
summary(mod_log)
## 
## Formula: Acumulado ~ SSlogis(Dias, phi1, phi2, phi3)
## 
## Parameters:
##       Estimate Std. Error t value Pr(>|t|)    
## phi1 3.969e+04  1.123e+03   35.33   <2e-16 ***
## phi2 1.122e+02  5.167e-01  217.13   <2e-16 ***
## phi3 9.368e+00  1.279e-01   73.25   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 164.3 on 61 degrees of freedom
## 
## Number of iterations to convergence: 1 
## Achieved convergence tolerance: 9.344e-07
p_log1 <- max(datos_log$Dias)
p_log2 <- round(p_log1+5, -1)
p_log3 <- p_log2 + 15
p_log4 <- p_log3 + 15

pred_log <- predict(mod_log,data.frame(Dias = c(p_log1, p_log2, p_log3, p_log4)))
max_pred <-round(pred_log[4]+500,-3) 
pred_log
## [1] 22802.28 27671.01 36491.00 38997.84
## attr(,"gradient")
##           phi1        phi2      phi3
## [1,] 0.5745591 -1035.49864 -311.1435
## [2,] 0.6972387  -894.24693 -745.9656
## [3,] 0.9194799  -313.63338 -763.7917
## [4,] 0.9826459   -72.23958 -291.5892
dia1_log <- min(datos3$FECHA_INGRESO)

alpha <- coef(mod_log)  #Coeficientes
plot(Acumulado ~ Dias, data = datos_log, main = "Modelo de crecimiento logístico para SARS-Cov2 en México", 
     xlab = "Días", ylab = "Casos positivos acumulados", xlim = c(1, p_log4+15), ylim = c(1, max_pred))  #Casos
curve(alpha[1]/(1 + exp(-(x - alpha[2])/alpha[3])), add = T, col = "blue")  #Modelo
points(p_log2, pred_log[2], pch = "x", cex = 1.3)
points(p_log3, pred_log[3], pch = "x", cex = 1.3)
points(p_log4, pred_log[4], pch = "x", cex = 1.3)
text(p_log2, pred_log[2], labels = paste0(dia1_log + p_log2, '\n', "[", round(pred_log[2], -2) ," casos]"), 
     adj = c(1.1,0))
text(p_log3, pred_log[3], labels = paste0(dia1_log + p_log3, '\n', "[", round(pred_log[3], -2) ," casos]"), 
     adj = c(1.1,0))
text(p_log4, pred_log[4], labels = paste0(dia1_log + p_log4, '\n', "[", round(pred_log[4], -2) ," casos]"), 
     pos = 1, offset = 0.8)