library(dplyr)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
library(shiny)
library(stringr)
library(DT)
##
## Attaching package: 'DT'
## The following objects are masked from 'package:shiny':
##
## dataTableOutput, renderDataTable
library(FactoClass)
## Loading required package: ade4
## Loading required package: ggplot2
## Loading required package: ggrepel
## Loading required package: xtable
## Loading required package: scatterplot3d
#setwd("C:/Users/Home/Documents/Laboral 2021/Minjusticia/cluster_12Agosto2021/scripts/app")
setwd("D:/Users/DAVID FELIPE TAUTIVA/Downloads/Indice_conflictividad_13oct2021/scripts/app")
divipolaPDET <- readRDS("divipolaPDET.rds")
divipolaPDET$PDET <- ifelse(!is.na(divipolaPDET$NombreSubregion), 1, 0)
#dptos <- divipolaPDET$`Código Departamento`
#names(dptos) <- divipolaPDET$`Nombre Departamento`
dptos <- unique(divipolaPDET$`Nombre Departamento`)
#mpio <- divipolaPDET$`Código Municipio`
#names(mpio) <- divipolaPDET$`Nombre Municipio`
mpio <- divipolaPDET$`Nombre Municipio`
divipolaPDET <- divipolaPDET %>% group_by(`Código Departamento`) %>% mutate(pdet_dpto = sum(PDET))
divipolaPDET$pdet_dpto <- ifelse(divipolaPDET$pdet_dpto >= 1, 1, 0)
names(divipolaPDET)[1] <- "CODDPTO"
names(divipolaPDET)[2] <- "CODMPIO"
#setwd("../")
#setwd("outputs/1.Resultados_Clasificaciones")
setwd("D:/Users/DAVID FELIPE TAUTIVA/Downloads/Indice_conflictividad_13oct2021/outputs/1.Resultados_Clasificaciones")
#setwd("C:/Users/Home/Documents/Laboral 2021/Minjusticia/cluster_12Agosto2021/outputs/1.Resultados_Clasificaciones")
indicadores <- readRDS("indicadores_Clasifica.rds")
indicadores <- left_join(indicadores, divipolaPDET, by = "CODMPIO")
nombre_indicadores <- c('ind_AEL','ind_OSP', 'ind_US','ind_CONF1', "ind_CI", 'ind_CONV',
'ind_EI','ind_F','ind_SP1', 'ind_SAL',"ind_Conf", "IPM", "ind_Bienes", "ind_Poblacion",
"ind_Desemp")
etiqueta_variables <- c("Economía legal", "Ordenamiento social de la propiedad", "Uso del suelo",
"Incidencia Conflicto armado", "Conflicto intercultural", "Convivencia",
"Economía ilegal", "Familia", "Servicios públicos", "Salud",
"Índice de conflictividad", "Pobreza multidimensional",
"ïndice de bienes públicos", "índice de población", "Índice de desempeño municipal")
df_carac <- readRDS("df_carac.rds")
# Define UI for application that draws a histogram
ui <- fluidPage(
tags$div(class = "header", checked = NA, tags$img(src = "logo.png"), tags$h1("Análisis de indicadores de conflictividad"),align="center"),
br(),
sidebarLayout(
sidebarPanel(tags$style(".well {background-color:#6e45f5;}"),
h4("Seleccione el municipio de interés:"),
checkboxInput("Pdet", "Seleccione UNICAMENTE municipios PDET", value = FALSE),
selectInput("Departamento", "Seleccione departamento",
names(dptos)),
selectInput("Municipio", "Seleccione municipio", names(mpio)), br(),
h4("Cluster municipio seleccionado"),
h4(textOutput("Cluster")),
span(h3(textOutput("ClusterCalculado")), style="color:red", align = "center"),
h4(textOutput("TipoRanking")),
tableOutput("Ranking")),
# Show a plot of the generated distribution
mainPanel(
tabsetPanel(type = "tabs",
tabPanel("Indice Conflictividad", h3(textOutput("texto_municipio")), br(),
DT::DTOutput("tabla_conflictividad"),
br(), br(),h3(textOutput("texto_municipiosCompletosPdet")), br(),
DT::DTOutput("Resumen_Municipios")),
tabPanel("Indicadores conflictividad y cluster", DT::DTOutput("TablaCompleta")),
tabPanel("Clasificación", verbatimTextOutput("CaracterizacionCluster"),
plotOutput("GraficoCluster"))
)
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output, session) {
observe({ updateSelectInput(session,
inputId="Departamento",
choices= if(input$Pdet == 1){
unique(divipolaPDET[divipolaPDET$pdet_dpto == 1,]$`Nombre Departamento`)
} else dptos
)
})
observe({ updateSelectInput(session,
inputId="Municipio",
choices= if(input$Pdet == 1){
unique(divipolaPDET[divipolaPDET$`Nombre Departamento` == input$Departamento & divipolaPDET$PDET == 1 & divipolaPDET$pdet_dpto == 1 ,]$`Nombre Municipio`)
} else unique(divipolaPDET[divipolaPDET$`Nombre Departamento` == input$Departamento,]$`Nombre Municipio`)
)
})
output$cluster <- renderText({
paste0("Resultados indices de conflictividad ", input$Municipio, " (", input$Departamento, ")")
})
output$ClusterCalculado <- renderText({
(indicadores %>% filter(`Nombre Departamento` == input$Departamento &
`Nombre Municipio` == input$Municipio))$CLUSTER_COMBINADO
})
output$texto_municipio <- renderText({
paste0("Resultados indices de conflictividad ", input$Municipio, " (", input$Departamento, ")")
})
output$texto_municipiosCompletosPdet <- renderText({
paste0("Resultados indices de conflictividad ", ifelse(input$Pdet == 1, "(Municipios PDET)", "(Todos los municipios)"))
})
output$TipoRanking <- renderText({
ifelse(input$Pdet == 1, "Ranking sobre municipios PDET:", "Ranking sobre todos los municipios:")
})
output$Ranking <- renderTable({
if(input$Pdet == 1){
indicadores_red <- indicadores[indicadores$`MUNICIPIOS PDET` == 1, ]
} else {
indicadores_red <- indicadores
}
Ranking <- vector(mode = "list", length = 15)
for(i in 1:length(nombre_indicadores)){
Ranking[[i]] = rank(-indicadores_red[[nombre_indicadores[i] ]])[indicadores_red$`Nombre Departamento` == input$Departamento & indicadores_red$`Nombre Municipio` == input$Municipio][1]
}
Ranking = unlist(Ranking) %>% na.omit()
#RankingDF <- as.data.frame(Ranking)
RankingDF <- data.frame(Ranking = Ranking[1:11], Indicador = etiqueta_variables)
RankingDF$TotalMpios <- nrow(indicadores_red)
RankingDF %>% select(Indicador, Ranking, TotalMpios)
})
output$tabla_conflictividad <- DT::renderDT({
salida <- indicadores[indicadores$`Nombre Departamento` == input$Departamento &
indicadores$`Nombre Municipio` == input$Municipio & !is.na(indicadores$ind_Conf),
nombre_indicadores ]
salida <- as.data.frame(lapply(salida, round, digits = 3))[1,]
names(salida) <- etiqueta_variables
salida
})
output$TablaCompleta <- DT::renderDT({
tablaCompleta <- indicadores[c("CODMPIO", "Dpto", "Mpio", "Region funcional", "Sistema ciudades", "MUNICIPIOS PDET",
"ind_Bienes", "ind_Desemp", "ind_SocDem", "distancia_centroide",
"CLUSTER_VECINO", "CLUSTER_CONSTRUIDO", "CLUSTER_COMBINADO",
nombre_indicadores)]
names(tablaCompleta)[names(tablaCompleta) %in% nombre_indicadores] <- etiqueta_variables
for(i in which(names(tablaCompleta) %in% nombre_indicadores)){
tablaCompleta[,i] <- round(tablaCompleta[,i], 3)
}
tablaCompleta
})
output$GraficoCluster <- renderPlot({
ggplot(data = indicadores, aes(x = CLUSTER_COMBINADO, fill = "darkblue")) + geom_bar() + xlab("Cluster") + ylab("Cuenta") + ggtitle("Cluster para todos los municipios:") + theme_bw()
})
output$CaracterizacionCluster <- renderPrint({
indicadores_mpiossel <- indicadores[!is.na(indicadores$CLUSTER_CONSTRUIDO),]
cluster.carac(indicadores_mpiossel[c(nombre_indicadores[-11], "ind_SocDem", "ind_Bienes", "ind_Desemp")],
indicadores_mpiossel$CLUSTER_CONSTRUIDO ,"co",2.0) # continuous variables
})
output$Resumen_Municipios <- DT::renderDT({
if(input$Pdet == 1){
indicadores_red <- indicadores[indicadores$`MUNICIPIOS PDET` == input$Pdet , nombre_indicadores]
} else {
indicadores_red <- indicadores[,nombre_indicadores]
}
names(indicadores_red) <- etiqueta_variables
indicadores_red <- as.data.frame.matrix(summary(indicadores_red))
for(j in 1:ncol(indicadores_red)){
indicadores_red[,j] <- indicadores_red[,j]
indicadores_red[,j] <- as.numeric(str_trim(sub('.*:', '', indicadores_red[,j])))
}
indicadores_red <- as.data.frame(lapply(indicadores_red, round, digits = 3))
row.names(indicadores_red) <- c("Mínimo", "Percentil 25", "Mediana", "Promedio", "Percentil 75",
"Máximo", "Faltante")
colnames(indicadores_red) <- etiqueta_variables
indicadores_red
})
}
# Run the application
shinyApp(ui = ui, server = server)
## PhantomJS not found. You can install it with webshot::install_phantomjs(). If it is installed, please make sure the phantomjs executable can be found via the PATH variable.
Shiny applications not supported in static R Markdown documents