es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

Regresión en la aplicación shinyApp con selección dinámica de variables.

Quiero realizar regresiones lineales de la variable Feature_A y quiero que el usuario seleccione dinámicamente la otra variable. También quiero mostrar estadísticas sobre el ajuste general de mi modelo predictivo, R2 ajustado, cada coeficiente estimado del modelo y los p-valores de los coeficientes.
A continuación está lo que pude descubrir. No hace falta decir que no funciona. He estado luchando con esto y cualquier ayuda será muy apreciada.

library(shiny)
library(ggplot2)
library(dplyr)
library(purrr)

Feature_A <- c(1, 2, 1, 4, 2)
Feature_B <- c(4, 5, 6, 6, 6)
Feature_C <- c(22, 4, 3, 1, 5)
df <- data.frame(Feature_A, Feature_B, Feature_C)

ui <- fluidPage(

  titlePanel(title = h4("Regression")),

  sidebarLayout(

    sidebarPanel(
      selectInput('ip', 'Select an Explanatory Variable', names(df)),
      actionButton(inputId = "btn1", label = "Regression Plot"),
      actionButton(inputId = "btn2", label = "Show Stats")
    ),

    mainPanel(
      "main panel",
      regOutput("regplot"),
      verbatimTextOutput("summary")
    )
  )
)

server <- function(input, output, session) {

  lm_fit <- lm(Feature_A ~ input$ip, data = df)

  summary_stats <- eventReactive(input$btn2, {
    summary(lm_fit)
  })

  regression_plot <- eventReactive(input$btn1, {
    ggplot(data = df, aes(x = input$ip, y = Feature_A)) +
      geom_point(color = 'blue') +
      geom_smooth(method = "lm", se = FALSE)
  })

  output$regplot <- renderPlot({
    regression_plot()
  })

  output$summary <- renderPrint({
    summary_stats()
  })

}

shinyApp(ui, server)
Tags:  , , , ,

Answer

  1. Avatar for davy.ai

    Para realizar regresiones lineales de Feature_A y permitir al usuario seleccionar la otra variable de forma dinámica, podemos crear un selectInput en el sidebarPanel de la interfaz de Shiny y utilizar la variable seleccionada como entrada para el código de regresión en la función del servidor. Para mostrar las estadísticas sobre el ajuste del modelo predictivo, podemos utilizar summary() en el objeto lm y mostrarlo utilizando renderPrint() en la salida de Shiny.

    Aquí tienes un código actualizado que debería funcionar:

    library(shiny)
    library(ggplot2)
    library(dplyr)
    library(purrr)
    
    Feature_A <- c(1, 2, 1, 4, 2)
    Feature_B <- c(4, 5, 6, 6, 6)
    Feature_C <- c(22, 4, 3, 1, 5)
    df <- data.frame(Feature_A, Feature_B, Feature_C)
    
    # Define UI for application
    ui <- fluidPage(
    
      # Panel de Encabezado o Título
      titlePanel(title = h4("Regresión")),
    
      sidebarLayout(
        # Panel de la barra lateral
        sidebarPanel(
          selectInput('input_var', 'Selecciona una Variable Explicativa', names(df)),
          actionButton(inputId = "btn1", label = "Gráfico de Regresión"),
          actionButton(inputId = "btn2", label = "Mostrar Estadísticas")
        ),
    
        # Panel Principal
        mainPanel("panel principal", plotOutput("regplot"), verbatimTextOutput("summary"))
      )
    )
    
    server <- function(input, output, session) {
    
      # Función reactivo para el gráfico de regresión
      regression_plot <- reactive({
        ggplot(data = df, aes(x = df[, paste0(input$input_var)], y = Feature_A)) + 
          geom_point(color = 'blue') +
          geom_smooth(method = "lm", se = FALSE)
      })
    
      # Función reactivo para las estadísticas de resumen de regresión
      summary_stats <- reactive({
        lm_fit <- lm(Feature_A ~ df[, paste0(input$input_var)], data = df)
        summary(lm_fit)
      })
    
      output$regplot <- renderPlot({ regression_plot() })
      output$summary <- renderPrint({ summary_stats() })
    
    }
    
    shinyApp(ui, server)
    

    Ten en cuenta que utilizamos paste0(input$input_var) para obtener el nombre de la columna de forma dinámica a partir de la variable seleccionada en selectInput. Además, creamos dos funciones reactivas regression_plot y summary_stats que se activan mediante los botones de acción en el panel lateral. Por último, utilizamos renderPlot y renderPrint para mostrar la salida de estas funciones en la interfaz de Shiny.

Comments are closed.