简体   繁体   中英

R Shiny: updateSelectInput based on reactive dataframe

I have a shiny app where a user filters the article column of my dataset depending on the articles he wants to see. Those articles are then displayed in a table. The articles react as actionbutton with a custom function on a click. I want that whenever a user clicks on a certain article, this article is selected in selectInput . Nevertheless I have no idea which value to pass to the selected attribute of updateSelectInput .

I have put three question marks in the place where I am stuck. By removing the three questionmarks the code is executable. Any help appreciated

library(shiny)
library(tidyverse)
library(kableExtra)
library(formattable)

df = tibble(article=c("one", "two", "three", "four", "five", "six"),
            group=c("a", "a", "a", "b", "b", "b"),
            sales=c(12,13,14,43,50,45))

ui = fluidPage(
    
    sidebarPanel(
        radioButtons(inputId = "select_a", label = "Choose a group", choices = unique(df$group), selected = "a"),
        htmlOutput(outputId = "table")),
    
    sidebarPanel(
        selectInput(inputId = "select_b", label = "Choose an article", choices = df$article, selected = "one")
    )
    
)

server = function(input, output, session){
    
    shinyInput <- function(FUN, len, id, labels, ...) {
        inputs <- character(len)
        for (i in seq_len(len)) {
            inputs[i] <- as.character(FUN(paste0(id, i), label = labels[i], ...))
        }
        inputs
    }
    
    df_reactive = reactive({
        df %>% filter(group == input$select_a) %>%
            mutate(article = shinyInput(actionButton, n(), 'button_', labels = article, onclick = 'Shiny.onInputChange(\"select_button\", this.id)'))
    })
    
    output$table = function(){
        df_reactive() %>%
            kable("html", escape = F, align = "c") %>%
            kable_styling(bootstrap_options = c("striped", "condensed", "responsive"), full_width = F, position = "center") %>%
            scroll_box(width = "100%", height = "auto")
    }
    
    observeEvent(input$select_button, {
        updateSelectInput(session = session, inputId = "select_b", selected = ???)
    })
    
    
}

shinyApp(ui = ui, server = server)

Perhaps you can use this.innerText to retrieve the article here:

mutate(article = shinyInput(actionButton, n(), 'button_', labels = article, 
                            onclick = 'Shiny.onInputChange(\"select_button\", this.innerText)'))

And then input$select_button will contain the text string to select :

updateSelectInput(session = session, inputId = "select_b", selected = input$select_button) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM