R/mod_cv_rlr.R

Defines functions mod_cv_rlr_server mod_cv_rlr_ui

#' cv_rlr UI Function
#'
#' @description A shiny Module.
#'
#' @param id,input,output,session Internal parameters for {shiny}.
#'
#' @noRd 
#'
#' @importFrom shiny NS tagList 
mod_cv_rlr_ui <- function(id){
  ns <- NS(id)
  
  tagList(
    tabBoxPrmdt(
      id = ns("Boxrlr"), 
      tabPanel(title = p(labelInput("seleParModel"),class = "wrapper-tag"), value = "tabCVrlrModelo",
               div(col_6(selectizeInput(
                 ns("sel_kernel"), labelInput("selectAlg"), multiple = T,
                 choices = list("Ridge" = 0, "Lasso" = 1))),
                   col_6(radioSwitch(ns("scale_cvrlr"), "escal", c("si", "no")))),
               div(col_12(id = ns("texto"),
                          style = "display:block",withLoader(verbatimTextOutput(ns("txtcvrlr")), 
                                                             type = "html", loader = "loader4"))),
               hr(style = "border-top: 2px solid #cccccc;" ),
               actionButton(ns("btn_cv_rlr"), labelInput("generar"), width  = "100%" ),br(),br()),
      tabPanel(title = p(labelInput("indices"),class = "wrapper-tag"), value = "tabCVrlrIndices",
               div(col_4(div(id = ns("row"), shiny::h5(style = "float:left;margin-top: 15px;", labelInput("selectInd"),class = "wrapper-tag"),
                             tags$div(class="multiple-select-var",
                                      selectInput(inputId = ns("cvcv_glo"),label = NULL,
                                                  choices =  "", width = "100%")))),
                   col_4(),
                   col_4(div(id = ns("row"), shiny::h5(style = "float:left;margin-top: 15px;", labelInput("tipoGrafico"),class = "wrapper-tag"),
                             tags$div(class="multiple-select-var",
                                      selectInput(inputId = ns("plot_type_p"),label = NULL,
                                                  choices =  c("lineas", "barras",  "error"), width = "100%")))), hr()),
               div(col_12(echarts4rOutput(ns("e_rlr_ind"), width = "100%", height = "70vh"))))
    )
    
  )
}
    
#' cv_rlr Server Functions
#'
#' @noRd 
mod_cv_rlr_server <- function(input, output, session, updateData, codedioma){
  ns <- session$ns
  
  
  M <- rv(MCs.rlr = NULL, grafico = NULL, er = NULL, ea = NULL, corr = NULL, times = 0, summary = NULL)
  
  observeEvent(codedioma$idioma, {
    
    nombres <- list("lineas", "barras",  "error")
    names(nombres) <- tr(c("grafLineas", "grafBarras", "grafError"),codedioma$idioma)
    indices <- list(0, 1, 2, 3)
    names(indices) <- tr(c("RMSE", "MAE", "ER", "correlacion"),codedioma$idioma) 
    updateSelectInput(session, "cvcv_glo", choices = indices, selected = 0)
    updateSelectInput(session, "plot_type_p", choices = nombres, selected = "lineas")
  })
  
  observeEvent(c(updateData$datos, updateData$variable.predecir), {
    M$MCs.rlr <- NULL
    M$grafico <- NULL
    M$ea   <- NULL
    M$er   <- NULL
    M$corr <- NULL
    M$times      <- 0
    datos        <- updateData$datos
    
    if(!is.null(datos)){
      updateRadioSwitch(session,"switch_scale_rlr","TRUE")
      
      updateSelectizeInput(session, "sel_kernel", selected = "")
    }
  })
  
  output$txtcvrlr <- renderPrint({
    input$btn_cv_rlr
    M$MCs.rlr <- NULL
    M$grafico <- NULL
    M$ea   <- NULL
    M$er   <- NULL
    M$corr <- NULL
    tryCatch({
      kernels   <- isolate(input$sel_kernel)
      cant.vc   <- isolate(updateData$numValC)
      MCs.rlr   <- vector(mode = "list")
      datos     <- isolate(updateData$datos)
      numGrupos <- isolate(updateData$numGrupos)
      grupos    <- isolate(updateData$grupos)
      scales    <- isolate(input$scale_cvrlr)
      variable  <- updateData$variable.predecir
      var_      <- paste0(variable, "~.")
      nombres   <- vector(mode = "character", length = length(kernels))
      
      alpha_labels <- kernels
      alpha_labels[which(alpha_labels == 0)] = "Ridge"
      alpha_labels[which(alpha_labels == 1)] = "Lasso"
      
      if(length(kernels)<1){
        if(M$times != 0)
          showNotification("Debe seleccionar al menos un kernel")
      }
      for (kernel in 1:length(kernels)){
        MCs.rlr[[paste0("MCs.",alpha_labels[kernel])]] <- vector(mode = "list", length = cant.vc)
        nombres[kernel] <- paste0("MC.",alpha_labels[kernel])
      }
      for (i in 1:cant.vc){
        MC.rlr <- vector(mode = "list", length = length(kernels))
        names(MC.rlr) <- nombres
        for (kernel in 1:length(kernels)){
          MC.rlr[[kernel]] <- vector(mode = "list", 4)
          names(MC.rlr[[kernel]]) <- c("Raiz.Error.Cuadratico", "Error.Absoluto", "Error.Relativo", "Correlacion")
        }
        
        for (k in 1:numGrupos){
          muestra   <- grupos[[i]][[k]]
          ttraining <- datos[-muestra, ]
          ttesting  <- datos[muestra, ]
          
          for (j in 1:length(kernels)){
            modelo      <- rlr_model(data = ttraining, variable.pred = variable,
                                     alpha = kernels[j], standardize = as.logical(scales))
            
            prediccion  <- rlr_prediction(modelo, 
                                          ttesting, 
                                          variable)
            MC          <- general_indices(ttesting[,variable], prediccion)
            MC.rlr[[j]] <- Map(c, MC.rlr[[j]], MC)
            
          }
        }
        
        for (l in 1:length(MCs.rlr)){
          MCs.rlr[[l]][[i]] <-  sapply(MC.rlr[[l]],mean)
        }
      }
      
      M$MCs.rlr  <- MCs.rlr
      
      resultados <- indices.cv(cant.vc, alpha_labels, MCs.rlr)
      M$grafico  <- resultados$grafico
      M$ea   <- resultados$ea
      M$er   <- resultados$er
      M$corr <- resultados$corr
      M$summary <- summary_indices_v(datos[[variable]])
      isolate(codedioma$code <- append(codedioma$code, cv_rlr_code(variable, cant.vc, numGrupos)))
      
      print(MCs.rlr)
      
    },error = function(e){
      M$MCs.rlr <- NULL
      M$grafico <- NULL
      M$ea   <- NULL
      M$er   <- NULL
      M$corr <- NULL
      M$times    <- 0 
      return(invisible(""))
    })
  })
  
  output$e_rlr_ind  <-  renderEcharts4r({
    idioma <- codedioma$idioma
    tryCatch({
      indice  <- input$cvcv_glo
      type    <- input$plot_type_p
      grafico <- M$grafico
      if(!is.null(grafico)){
        label <- switch (indice,
                         "0" = tr("RMSE",idioma),
                         "1" = tr("MAE",idioma),
                         "2" = tr("ER",idioma),
                         "3" = tr("correlacion",idioma)
        )
        grafico$value <- switch (indice,
                                 "0" = grafico$value,
                                 "1" = M$ea,
                                 "2" = M$er,
                                 "3" = M$corr
        )
        grafico$name <-  tr(grafico$name, idioma)
        p <- ifelse(indice == "2", TRUE, FALSE)
        switch (type,
                "barras" = return( resumen.barras(grafico, labels = c(label,"Kernel",tr(c("maximo","minimo", "q1", "q3"), idioma)) ,percent = p, vals = M$summary)),
                "error" = return( resumen.error(grafico, labels = c(label, "Kernel", tr(c("maximo","minimo", "q1", "q3"), idioma)),percent = p, vals = M$summary)),
                "lineas" = return( resumen.lineas(grafico, labels = c(label, tr(c("crossval", "maximo","minimo", "q1", "q3"), idioma)), percent = p, vals = M$summary))
        )
      }
      else
        return(NULL)
    },error = function(e){
      showNotification(e)
      return(NULL)
    })
  })
  
}
    
## To be copied in the UI
# mod_cv_rlr_ui("cv_rlr_1")
    
## To be copied in the server
# mod_cv_rlr_server("cv_rlr_1")

Try the regressoR package in your browser

Any scripts or data that you put into this service are public.

regressoR documentation built on July 9, 2023, 5:26 p.m.