数据模拟介绍
-
代码用于投币游戏的模拟,可以手动设置游戏次数(0-500)、每次游戏中硬币抛出的次数(1-50)以及每次抛射硬币的正面概率(0-1)。
-
直方图可以展示游戏结束后,每次游戏的硬币得分情况(正面1分,反面0分)。
# R code of coin game in shiny
# load package
library(shiny)
## Warning: 程辑包'shiny'是用R版本4.1.1 来建造的
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Coin game"),
# Sidebar with a slider input for number of games, coins and probability of head
sidebarLayout(
sidebarPanel(
sliderInput("no.game",
"Number of games:",
min = 0,
max = 500,
value = 500),
sliderInput("no.coins",
"Number of coins per game:",
min = 1,
max = 50,
value = 50),
sliderInput("prob",
"Probability of head in one coin:",
min = 0,
max = 1,
value = 0.5)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot"),
br(), br(),
# verbatimTextOutput("stats"),
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output){
output$distPlot <- renderPlot({
# generate bins based on input$bins from ui.R
exp <- rbinom(input$no.game, input$no.coins, input$prob)
bins <- seq(0, 50, length.out = 50)
# draw the histogram with the score of coins per game
hist(exp,
breaks = bins,
xlab ="Score of coins per game",
ylab ="Frequency",
main = "Histogram of coin game",
col = 'darkgray',
border = 'white')
curve(dnorm(x, mean = mean(exp), sd = sd(exp)) * input$no.game,
col = "red",
add = TRUE)
})
# output$stats <- renderPrint({
# exp <- rbinom(input$no.game, input$no.coins, input$prob)
# shapiro.test(exp)
# })
}
# Run the application
shinyApp(ui = ui, server = server)
##
## Listening on http://127.0.0.1:7437