【问题标题】:R Shiny: updateSelectInput based on reactive dataframeR Shiny:基于反应数据框的 updateSelectInput
【发布时间】:2020-12-20 13:02:37
【问题描述】:

我有一个闪亮的应用程序,用户根据他想查看的文章过滤我的数据集的文章列。然后将这些文章显示在表格中。文章通过单击自定义功能作为操作按钮做出反应。 我希望每当用户点击某篇文章时,该文章在selectInput 中被选中。尽管如此,我不知道将哪个值传递给updateSelectInputselected 属性。

我在卡住的地方放了三个问号。通过删除三个问号,代码是可执行的。 任何帮助表示赞赏

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)

【问题讨论】:

    标签: r shiny reactive


    【解决方案1】:

    或许你可以使用this.innerText在这里检索文章:

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

    然后input$select_button将包含select的文本字符串:

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

    【讨论】:

    • 这很好用,我一直在寻找这样的东西,但由于我根本不熟悉 Javascript,所以我永远无法想出解决方案。如果您能详细说明this.innerText,那就太好了,以便我正确理解这里发生的事情。
    • @lucaskr innerText 属性是 HTML 元素的“渲染”纯文本。如果您使用光标突出显示元素的内容并复制,它通常是您会得到的文本。在这种情况下,它将是按钮的文本标签。当您动态创建按钮时,您拥有&lt;button class = "btn"...&gt;labelhere&lt;/button&gt;,因此“labelhere”将是从this.innerText 返回的文本。
    猜你喜欢
    • 2014-06-16
    • 2017-01-17
    • 2019-02-15
    • 2020-02-12
    • 2019-12-17
    • 1970-01-01
    • 2019-05-15
    • 2015-08-07
    • 2020-09-29
    相关资源
    最近更新 更多