正如@guasi在评论中指出的那样,问题是
numericInput
缺少默认值。在提供这个值后,我也清楚地发现,当反应值只能由单个字符串索引时,我试图使用值的向量来索引它们。因此,我使用
purrr::map
对值的矢量进行运算。由于这会生成一个列表,因此我未列出以向
hist
。
下面的修订代码生成了预期的直方图。
library(shiny)
library(shinyWidgets)
library(purrr)
ui <- fluidPage(
titlePanel("Title"),
fluidRow(
column("",
width = 10, offset = 1,
tags$h3("Filler"),
panel(
numericInput("n_params","How many fields?", min = 2, max = 100, value = 3),
uiOutput("param_fields"),
numericInput("n_sims","How many simulations?", min = 0, max = 100000, value = 10000),
actionButton("sampling", "Sample from this distribution!")
),
tags$h3("Plotted results!"),
plotOutput("plotted")
)
)
)
# Define server logic
server <- function(input, output) {
# Dynamically create a set of numeric input fields based on the
# number of parameters specified (fancy math symbols needed, ignore mathjax)
dynamic_list_of_numeric_fields <- reactive({
n_params <- req(input$n_params)
purrr::map(1:n_params,
~numericInput(paste0("alpha",.),
withMathJax(paste0("\\(\\alpha_{", . ,"}\\)"))))
})
# Render the parameter fields for user-input of values
output$param_fields <- renderUI({
div(
req(dynamic_list_of_numeric_fields())
)
})
# Create plot updated any time sampling button is pushed
plots <- eventReactive(input$sampling, {
# Get the user-input parameter values
n_params <- req(input$n_params)
param_ids <- paste0("alpha", 1:n_params)
param_vals <- input[[param_ids]]
# Histogram
hist(param_vals)
})
output$plot <- renderPlot({
plots()
})
}
shinyApp(ui = ui, server = server)