首页 > 解决方案 > 在 Shiny 中更新复选框值

问题描述

我正在尝试制作一个 Shiny 应用程序,它执行以下操作:

1)上传这样的文件:

X   Y
1   3
2   1
3   6
4   4

2) 按一个Run按钮,默认情况下将文件值加 2,如果选中一个框,则乘以 2,

3) 根据生成的值制作散点图。

我的问题是(i)我需要选中/取消选中该框,然后再次按下Run按钮以显示相应的图,并且(ii)该复选框on每次都会返回。

当我在不按下按钮的情况下选中/取消选中该框时,如何更新绘图Run?我试图将observe()andupdateCheckboxInput()函数放在eventReactive()块之外,但它根本不起作用。

我的代码:

library(shiny)
library(ggplot2)



ui <- fluidPage(
    fileInput(
        inputId = "input_file",
        label = "Choose an input file"
    ),
    actionButton(
        inputId = "run_button",
        label = "Run"
    ),
    checkboxInput(
        inputId = "operation_button",
        label = "multiply instead of summing",
        value = FALSE
    ),
    plotOutput(
        outputId = "my_plot"
    )
)


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

    my_data <- eventReactive(
        input$run_button,
        {
            inFile <- input$input_file
            if(is.null(inFile)){
                return(NULL)
            }

            my_in <- read.table(inFile$datapath, header = T, sep = "\t")

            my_function <- function(input, operation){
                if(operation == "sum"){
                    input <- input + 2
                }else if(operation == "multiply"){
                    input <- input * 2
                }

                return(input)
            }

            button_switch <- ifelse(input$operation_button == FALSE, "sum", "multiply")

            observe(
                {
                    updateCheckboxInput(session, "operation_button", "multiply instead of summing", value = button_switch)
                }
            )

            my_in <- my_function(my_in, button_switch)

        }
    )



    output$my_plot <- renderPlot(
        {
        my_df <- my_data()

        ggplot(my_df, aes(x=X, y=Y)) + 
        geom_point()
        }
    )
}


shinyApp(ui = ui, server = server)

标签: rshiny

解决方案


您可以eventReactive()依赖多个输入:

my_data <- eventReactive(c(input$run_button, input$operation_button),...)

推荐阅读