如何在Shiny中保留以前的输入?
我想展示估计值如何根据用户输入而变化。
例如,如果用户更改输入并且估计值上升,那么在某些面板中我想打印估计值上升。
为此,我想获取用户输入的序列,例如
> c(2,4,5,6)
[1] 2 4 5 6
Run Code Online (Sandbox Code Playgroud)
其中2,4,5,6是 之前获得的输入sliderInput。也就是说,首先,用户选择了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)
Run Code Online (Sandbox Code Playgroud)
您可以将先前值和实际值存储在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 = ",")
})
Run Code Online (Sandbox Code Playgroud)