先前在Shiny中输入

时间:2019-07-09 05:45:41

标签: r shiny

如何在Shiny中保留以前的输入?

我想展示估计如何根据用户输入而变化。

例如,如果用户更改了输入并且估计值上升了,那么在某些面板中我要打印出估计值上升。

为此,我想获得诸如

之类的用户输入序列
> c(2,4,5,6)
[1] 2 4 5 6

其中2,4,5,6sliderInput获得的先前输入。 也就是说,首先,用户选择了2,第二个选择的数字是4,等等。


修改

以下是@GyD的答案。

    library(shiny)
    # Define UI for application that draws a histogram
    ui <- fluidPage(

        # Application title
        titlePanel("Old Faithful Geyser Data"),

        # Sidebar with a slider input for number of bins 
        sidebarLayout(
            sidebarPanel(
                sliderInput("bins",
                            "Number of bins:",
                            min = 1,
                            max = 50,
                            value = 30)
            ),

            # Show a plot of the generated distribution
            mainPanel(
               verbatimTextOutput("print")
            )
        )
    )

    # print history of user input
    server <- function(input, output) {

        rv <- reactiveValues(prev_bins = NULL)
        observeEvent(input$bins, {
# If event occurs, then run the following append function
            rv$prev_bins <- c(rv$prev_bins, input$bins)
        })

        # Output
        output$print <- renderPrint({
            paste(rv$prev_bins, collapse = ",")
        })

        # output$print <- renderPrint({
        #    
        #     paste(s, input$bins,sep = ",")
        # })
    }

    # Run the application 
    shinyApp(ui = ui, server = server)

1 个答案:

答案 0 :(得分:1)

您可以将先前值和实际值存储在reactiveValues对象中:

rv$prev_bins初始化为NULL,然后在每次更改值时,都会将新值附加到向量上。

要仅保留先前值和当前值,而不使用所有值,请使用:rv$prev_bins <- c(tail(rv$prev_bins, 1), input$bins)

代码:

# Initialize reactive values
rv <- reactiveValues(prev_bins = NULL)

# Append new value to previous values when input$bins changes 
observeEvent(input$bins, {
  rv$prev_bins <- c(rv$prev_bins, input$bins)
})

# Output
output$print <- renderPrint({
  paste(rv$prev_bins, collapse = ",")
})

输出:

Output