AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 77736243
Accepted
firmo23
firmo23
Asked: 2023-12-30 22:33:18 +0800 CST2023-12-30 22:33:18 +0800 CST 2023-12-30 22:33:18 +0800 CST

Atualize pares de widgets brilhantes que afetam uns aos outros

  • 772

Tenho o shinyaplicativo abaixo em que o subconjunto inicial acontece a partir da 1ª entrada com os nomes. Então os valores disponíveis deverão passar para as outras quatro entradas e para a tabela.

Quero que os valores das outras 4 entradas sejam atualizados com base na escolha da primeira, mas também quando, por exemplo, eu selecionar o valor mínimo ou máximo, as datas mínima e máxima serão subdefinidas e vice-versa.

Apenas a 1ª entrada deve manter sempre a mesma quantidade de todos os nomes.

library(shiny)
library(shinydashboard)
library(shinyWidgets)
# Load necessary libraries
library(DT)

# Creating a sample dataframe
set.seed(123)
dates <- seq(as.Date("2023-01-01"), as.Date("2023-12-31"), by = "days")
numeric_values <- sample(1:100, length(dates), replace = TRUE)
names <- rep(c("Alice", "Bob", "Charlie"), length.out = length(dates))

df <- data.frame(Date = dates, Numeric = numeric_values, Name = names)

# Define UI
ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      pickerInput("namePicker", "Select Name:", choices = unique(df$Name),selected = unique(df$Name)[1], multiple = TRUE),
      uiOutput("numeric1"),
      uiOutput("numeric2"),
      uiOutput("date1"),
      uiOutput("date2")
    ),
    mainPanel(
      DTOutput("table")
    )
  )
)

# Define server logic
server <- function(input, output, session) {
  
  # Filter data based on selected names
  filtered_data <- reactive({
    req(input$namePicker)
    df_subset <- df[df$Name %in% input$namePicker, ]
    
    return(df_subset)
  })
  
  # Render the filtered data table
  output$table <- renderDT({
    datatable(filtered_data(), options = list(pageLength = 10))  # Customize datatable appearance if needed
  })
  
  # Render numeric range inputs dynamically
  output$numeric1 <- renderUI({
    numericInput("minNumeric", "Min Numeric Value:", min = min(df$Numeric), max = max(df$Numeric), value = min(df$Numeric))
  })
  output$numeric2 <- renderUI({
    numericInput("maxNumeric", "Max Numeric Value:", min = min(df$Numeric), max = max(df$Numeric), value = max(df$Numeric))
  })
  # Render date range inputs dynamically
  output$date1 <- renderUI({
    dateInput("minDate", "Min Date:", min = min(df$Date), max = max(df$Date), value = min(df$Date))
  })
  output$date2 <- renderUI({
    dateInput("maxDate", "Max Date:", min = min(df$Date), max = max(df$Date), value = max(df$Date))
  })
}

# Run the application
shinyApp(ui = ui, server = server)
  • 2 2 respostas
  • 71 Views

2 respostas

  • Voted
  1. Murad Khalilov
    2023-12-31T03:23:52+08:002023-12-31T03:23:52+08:00

    verifique a solução abaixo.

    library(shiny)
    library(shinydashboard)
    library(shinyWidgets)
    # Load necessary libraries
    library(DT)
    
    # Creating a sample dataframe
    set.seed(123)
    dates <- seq(as.Date("2023-01-01"), as.Date("2023-12-31"), by = "days")
    numeric_values <- sample(1:100, length(dates), replace = TRUE)
    names <- rep(c("Alice", "Bob", "Charlie"), length.out = length(dates))
    
    df <- data.frame(Date = dates, Numeric = numeric_values, Name = names)
    

    Simplifiquei um pouco o seu servidor, não é uma maneira eficiente de criar entradas no servidor e chamar uioutput na parte da UI, você pode escrever diretamente na UI ou apenas criar um valor de renderização para todas as entradas da UI.

    E também se você deseja atualizar suas 4 entradas dependendo da entrada do namePicker, então você precisa especificar como NULL para valores e irá atualizá-los no servidor

    # Define UI
    ui <- fluidPage(
      sidebarLayout(
        sidebarPanel(
          pickerInput("namePicker", "Select Name:", choices = unique(df$Name),selected = unique(df$Name)[1], multiple = TRUE),
          numericInput("minNumeric", "Min Numeric Value:", value = NULL),
          numericInput("maxNumeric", "Max Numeric Value:", value = NULL),
          dateInput("minDate", "Min Date:", value = NULL),
          dateInput("maxDate", "Max Date:", value = NULL)
        ),
        mainPanel(
          DTOutput("table")
        )
      )
    )
    

    Usei dois observeEvent no Server, primeiro: para atualizar as entradas minnumeric e maxnumeric de acordo com o que você escolher para pickerName, e segundo: pelo que entendi corretamente mindate e maxdate de acordo com qual outra variável foi escolhida. conforme você vê o que escolheu no nome do seletor, ele atualizará automaticamente os valores de entrada

    # Define server logic
    server <- function(input, output, session) {
      
      observeEvent(input$namePicker, {
        # Filter the managers based on the selected country
        filtered <- df[df$Name %in% input$namePicker, ]
        
        # Update the choices for the numeric input
        updateNumericInput(session, "minNumeric", min = min(filtered$Numeric), max = max(filtered$Numeric), value = min(filtered$Numeric))
        updateNumericInput(session, "maxNumeric", min = max(filtered$Numeric), max = max(filtered$Numeric), value = max(filtered$Numeric))
      })
      
      
      observeEvent(c(input$namePicker, input$minNumeric, input$maxNumeric), {
        # Filter the managers based on the selected country
        filtered <- df[df$Name %in% input$namePicker & df$Numeric >= input$minNumeric & df$Numeric <= input$maxNumeric, ]
        
        # Update the choices for the numeric input
        updateDateInput(session, "minDate", min = min(filtered$Date), max = max(filtered$Date), value = min(filtered$Date))
        updateDateInput(session, "maxDate", min = max(filtered$Date), max = max(filtered$Date), value = max(filtered$Date))
      })
      
      
      
      # Filter data based on selected names
      filtered_data <- reactive({
        req(input$namePicker)
        df_subset <- df[df$Name %in% input$namePicker &
                          df$Numeric >= input$minNumeric &
                          df$Numeric <= input$maxNumeric &
                          df$Date >= input$minDate &
                          df$Date <= input$maxDate,
                        ]
        
        return(df_subset)
      })
      
      # Render the filtered data table
      output$table <- renderDT({
        datatable(filtered_data(), options = list(pageLength = 10))  # Customize datatable appearance if needed
      })
      
    }
    
    # Run the application
    shinyApp(ui = ui, server = server)
    
    

    Espero que esta solução o ajude em seu projeto, caso tenha alguma dúvida entre em contato.

    • 1
  2. Best Answer
    polkas
    2023-12-31T19:09:13+08:002023-12-31T19:09:13+08:00

    DR Todas as entradas influenciam umas às outras, o que foi feito dependendo obervedos dados filtrados finais. Existem dois conjuntos de dados filtrados, um de inicialização e outro conectado com entradas numéricas/data. A atualização das entradas é desativada quando a seleção está vazia (com if).

    Quando descubro essa questão, o primeiro tópico conectado é a Filtragem Hierárquica como estratégia alternativa para filtros/seleções dependentes.

    library(shiny)
    library(shinydashboard)
    #> 
    #> Attaching package: 'shinydashboard'
    #> The following object is masked from 'package:graphics':
    #> 
    #>     box
    library(shinyWidgets)
    # Load necessary libraries
    library(DT)
    #> 
    #> Attaching package: 'DT'
    #> The following objects are masked from 'package:shiny':
    #> 
    #>     dataTableOutput, renderDataTable
    
    # Creating a sample dataframe
    set.seed(123)
    dates <- seq(as.Date("2023-01-01"), as.Date("2023-12-31"), by = "days")
    numeric_values <- sample(1:100, length(dates), replace = TRUE)
    names <- rep(c("Alice", "Bob", "Charlie"), length.out = length(dates))
    
    df <- data.frame(Date = dates, Numeric = numeric_values, Name = names)
    
    # Define UI
    ui <- fluidPage(
      sidebarLayout(
        sidebarPanel(
          pickerInput("namePicker", "Select Name:", choices = unique(df$Name), selected = unique(df$Name)[1], multiple = TRUE),
          uiOutput("inputs")
        ),
        mainPanel(
          DTOutput("table")
        )
      )
    )
    
    # Define server logic
    server <- function(input, output, session) {
      # Filter data based on selected names
      filtered_data <- eventReactive(input$namePicker, {
        df_subset <- df[df$Name %in% input$namePicker, ]
        df_subset
      })
    
      # Render numeric range inputs dynamically
      output$inputs <- renderUI({
        tagList(
          numericInput(
            "minNumeric",
            "Min Numeric Value:",
            value = min(filtered_data()$Numeric),
            min = min(filtered_data()$Numeric),
            max = max(filtered_data()$Numeric)
          ),
          numericInput(
            "maxNumeric",
            "Max Numeric Value:",
            value = max(filtered_data()$Numeric),
            min = min(filtered_data()$Numeric),
            max = max(filtered_data()$Numeric)
          ),
          dateInput(
            "minDate",
            "Min Date:",
            min = min(filtered_data()$Date),
            max = max(filtered_data()$Date),
            value = min(filtered_data()$Date)
          ),
          dateInput(
            "maxDate",
            "Max Date:",
            min = min(filtered_data()$Date),
            max = max(filtered_data()$Date),
            value = max(filtered_data()$Date)
          )
        )
      })
    
      filtered_data_full <- eventReactive(
        list(input$minNumeric, input$maxNumeric, input$minDate, input$maxDate),
        {
          df_subset <- subset(filtered_data(), Numeric >= input$minNumeric & Numeric <= input$maxNumeric & Date >= input$minDate & Date <= input$maxDate)
          df_subset
        },
        ignoreInit = TRUE
      )
    
      observe({
        if (NROW(filtered_data_full())) {
          updateNumericInput(
            session,
            "maxNumeric",
            "Max Numeric Value:",
            value = max(filtered_data_full()$Numeric),
            min = min(filtered_data_full()$Numeric),
            max = max(filtered_data_full()$Numeric)
          )
          updateNumericInput(
            session,
            "minNumeric",
            "Min Numeric Value:",
            min = min(filtered_data_full()$Numeric),
            max = max(filtered_data_full()$Numeric),
            value = min(filtered_data_full()$Numeric)
          )
          updateDateInput(
            session,
            "minDate",
            "Min Date:",
            min = min(filtered_data_full()$Date),
            max = max(filtered_data_full()$Date),
            value = min(filtered_data_full()$Date)
          )
          updateDateInput(
            session,
            "maxDate",
            "Max Date:",
            min = min(filtered_data_full()$Date),
            max = max(filtered_data_full()$Date),
            value = max(filtered_data_full()$Date)
          )
        }
      })
    
      output$table <- renderDT({
        datatable(filtered_data_full(), options = list(pageLength = 10))
      })
    }
    
    # Run the application
    shinyApp(ui = ui, server = server)
    #> 
    #> Listening on http://127.0.0.1:4962
    

    Criado em 31/12/2023 com reprex v2.0.2

    • 1

relate perguntas

  • Adicionar número de série para atividade de cópia ao blob

  • A fonte dinâmica do empacotador duplica artefatos

  • Selecione linhas por grupo com 1s consecutivos

  • Lista de chamada de API de gráfico subscritoSkus estados Privilégios insuficientes enquanto os privilégios são concedidos

  • Função para criar DFs separados com base no valor da coluna

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    destaque o código em HTML usando <font color="#xxx">

    • 2 respostas
  • Marko Smith

    Por que a resolução de sobrecarga prefere std::nullptr_t a uma classe ao passar {}?

    • 1 respostas
  • Marko Smith

    Você pode usar uma lista de inicialização com chaves como argumento de modelo (padrão)?

    • 2 respostas
  • Marko Smith

    Por que as compreensões de lista criam uma função internamente?

    • 1 respostas
  • Marko Smith

    Estou tentando fazer o jogo pacman usando apenas o módulo Turtle Random e Math

    • 1 respostas
  • Marko Smith

    java.lang.NoSuchMethodError: 'void org.openqa.selenium.remote.http.ClientConfig.<init>(java.net.URI, java.time.Duration, java.time.Duratio

    • 3 respostas
  • Marko Smith

    Por que 'char -> int' é promoção, mas 'char -> short' é conversão (mas não promoção)?

    • 4 respostas
  • Marko Smith

    Por que o construtor de uma variável global não é chamado em uma biblioteca?

    • 1 respostas
  • Marko Smith

    Comportamento inconsistente de std::common_reference_with em tuplas. Qual é correto?

    • 1 respostas
  • Marko Smith

    Somente operações bit a bit para std::byte em C++ 17?

    • 1 respostas
  • Martin Hope
    fbrereto Por que a resolução de sobrecarga prefere std::nullptr_t a uma classe ao passar {}? 2023-12-21 00:31:04 +0800 CST
  • Martin Hope
    比尔盖子 Você pode usar uma lista de inicialização com chaves como argumento de modelo (padrão)? 2023-12-17 10:02:06 +0800 CST
  • Martin Hope
    Amir reza Riahi Por que as compreensões de lista criam uma função internamente? 2023-11-16 20:53:19 +0800 CST
  • Martin Hope
    Michael A formato fmt %H:%M:%S sem decimais 2023-11-11 01:13:05 +0800 CST
  • Martin Hope
    God I Hate Python std::views::filter do C++20 não filtrando a visualização corretamente 2023-08-27 18:40:35 +0800 CST
  • Martin Hope
    LiDa Cute Por que 'char -> int' é promoção, mas 'char -> short' é conversão (mas não promoção)? 2023-08-24 20:46:59 +0800 CST
  • Martin Hope
    jabaa Por que o construtor de uma variável global não é chamado em uma biblioteca? 2023-08-18 07:15:20 +0800 CST
  • Martin Hope
    Panagiotis Syskakis Comportamento inconsistente de std::common_reference_with em tuplas. Qual é correto? 2023-08-17 21:24:06 +0800 CST
  • Martin Hope
    Alex Guteniev Por que os compiladores perdem a vetorização aqui? 2023-08-17 18:58:07 +0800 CST
  • Martin Hope
    wimalopaan Somente operações bit a bit para std::byte em C++ 17? 2023-08-17 17:13:58 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve