我正在尝试创建一个 Bootstrap /中心极限定理的Shiny应用程序演示,它一般都能正常工作。然而,我打算有一个Shiny应用程序,每次点击“模拟”时,绘图都会刷新,并生成一个新的不同分布。然而,每次我打开应用程序并点击“模拟”时,绘图都保持静态和相同。
有没有人对如何解决/修复有什么想法?那将非常感激!
library(shiny)
library(tidyverse)
# Define the user interface for the app
ui <- fluidPage(
# Add a title and sidebar
titlePanel("Bootstrapped Distribution"),
sidebarLayout(
sidebarPanel(
sliderInput("num_sims", "Number of Simulations:",
min = 1, max = 10000, value = 100),
sliderInput("sampleSize", "Sample Size:",
min = 1, max = 10000, value = 100),
selectInput("distT", "Distribution Type:",
c("Normal" = "norm",
"Exponential" = "exp",
"Gamma" = "gam",
"Poisson" = "pois",
"Binomial" = "binom")),
actionButton("simulate", "Simulate")
),
# Add a plot to the main panel
mainPanel(plotOutput("dist_plot"))
)
)
# Define the server logic for the app
server <- function(input, output) {
# Create a reactive expression to simulate the bootstrapped distribution
#dist_data <- reactive({
dist_data <- reactive({
if(input$distT == "norm"){
bootstrapped_mean <- replicate(input$num_sims, mean(rnorm(input$sampleSize)))
}else if(input$distT == "exp"){
bootstrapped_mean <- replicate(input$num_sims, mean(rexp(input$sampleSize)))
}else if(input$distT == "gam"){
bootstrapped_mean <- replicate(input$num_sims, mean(rgamma(input$sampleSize, shape=1)))
}else if(input$distT == "pois"){
bootstrapped_mean <- replicate(input$num_sims, mean(rpois(input$sampleSize, lambda = 1)))
}else if(input$distT == "binom"){
bootstrapped_mean <- replicate(input$num_sims, mean(rbinom(input$sampleSize, size = 1, prob = .5)))
}
ggplot(data=tibble(mean=bootstrapped_mean), aes(x=mean)) +
geom_histogram(bins=30) + jtools::theme_apa()
})
# Update the plot when the "Simulate" button is clicked
observeEvent(input$simulate, {
output$dist_plot <- renderPlot({
dist_data()
})
}
)
}
1条答案
按热度按时间kqlmhetl1#
建议:
dist_data
返回 * 仅仅 * 数据,而不是试图把它也画出来。这个应用程序并没有从这一步中受益匪浅,但它是一个很好的方法来组织你正在做的事情。例如,如果您稍后添加了一个汇总随机数据的表,那么您就没有一种简单的方法让该表获取随机数据,因为
data_dist
返回的是ggplot grob,而不是原始数据。dist_data
React性模块中添加对input$simulate
的依赖项:这将导致每次按下按钮时重新生成随机数据。如果没有这个,数据将生成一次,并且永远不会重做。output$dist_plot
移出观察点(不再需要)。