虽然我能够生成正确数量的样本,并且这些样本的大小都是正确的,但每个样本都完全相同。
目前,我正在尝试创建一个演示中心极限定理的应用程序,特别是针对样本均值分布的情况。当我意识到直方图在x轴上具有相同的精确值时,我希望应用程序生成正确的采样分布,这表明每个样本的均值完全相同。
根据我自己的测试,我认为问题出在sample_i()React表达式上,因为后面的React表达式工作得很好。
我是否必须实现另一个React式表达式才能解决这个问题?
library(shiny)
ui <- fluidPage(
titlePanel("Demonstration of the Central Limit Theorem"),
fluidRow(
column(4, selectInput("dist", "Distribution",
c("Normal", "Uniform", "Poisson", "Binomial"))),
column(4, numericInput("n_sample", "Number of samples", value = 50)),
column(4, numericInput("size", "Sample size", value = 100))
),
tabsetPanel(
id = "params",
type = "hidden",
tabPanel("Normal",
numericInput("mean", "Mean", value = 0),
numericInput("sd", "SD", value = 1)
),
tabPanel("Uniform",
numericInput("min", "Min", value = 0),
numericInput("max", "Max", value = 1)
),
tabPanel("Poisson",
numericInput("r", "Rate", value = 1)
),
tabPanel("Binomial",
numericInput("p", "Probability of success", value = 0.5),
numericInput("n", "Number of trials", value = 10)
)
),
plotOutput("hist"),
verbatimTextOutput("length")
)
server <- function(input, output, session) {
observeEvent(input$dist, {
updateTabsetPanel(inputId = "params", selected = input$dist)
})
sample_i <- reactive({
switch(input$dist,
Normal = rnorm(input$size, input$mean, input$sd),
Uniform = runif(input$size, input$min, input$max),
Poisson = rpois(input$size, input$r),
Binomial = rbinom(input$size, input$n, input$p))
})
sample_dist <- reactive({
replicate(n = input$n_sample, sample_i())
})
sample_dist_mean <- reactive({
apply(sample_dist(), MARGIN = 2, mean) |>
unlist() |>
as.numeric()
})
output$hist <- renderPlot(hist(sample_dist_mean()))
output$length <- renderPrint(head(sample_dist(), n = 5))
}
shinyApp(ui, server)
请注意,当样本数设置为12时,控制台生成以下输出(通过输出的长度组件完成)。
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 0.5953571 0.5953571 0.5953571 0.5953571 0.5953571 0.5953571
[2,] 0.8323953 0.8323953 0.8323953 0.8323953 0.8323953 0.8323953
[3,] -1.0366900 -1.0366900 -1.0366900 -1.0366900 -1.0366900 -1.0366900
[4,] 2.1517537 2.1517537 2.1517537 2.1517537 2.1517537 2.1517537
[5,] -1.2565259 -1.2565259 -1.2565259 -1.2565259 -1.2565259 -1.2565259
[,7] [,8] [,9] [,10] [,11] [,12]
[1,] 0.5953571 0.5953571 0.5953571 0.5953571 0.5953571 0.5953571
[2,] 0.8323953 0.8323953 0.8323953 0.8323953 0.8323953 0.8323953
[3,] -1.0366900 -1.0366900 -1.0366900 -1.0366900 -1.0366900 -1.0366900
[4,] 2.1517537 2.1517537 2.1517537 2.1517537 2.1517537 2.1517537
[5,] -1.2565259 -1.2565259 -1.2565259 -1.2565259 -1.2565259 -1.2565259
1条答案
按热度按时间2wnc66cl1#
编辑:找到了新的解决方案。