Бейсбол симулятор - PullRequest
       25

Бейсбол симулятор

0 голосов
/ 27 марта 2019

Я пытаюсь создать симуляцию, в которой бейсболист либо попадает на базу, либо выходит на основе этих заданных вероятностей (Base = .32 и Out = .68). Когда он не получает «Out», он попадает домой в 20% случаев. Он может ходить на биту столько раз, сколько захочет. Но когда у него 40 аутов, симуляция останавливается. Я хочу знать, сколько хоум-ранов этот игрок дал при указанных выше условиях.

Я создал функцию, которая даст мне то, что я хочу выше. Но это не останавливается, когда есть 40 аутов. Я чувствую, что цикл по времени поможет, но я не слишком знаком с ними. Любые другие советы также будут полезны. Я новичок в R.

Player = function(n) {
 x = sample(c("Out","Base"), n , prob = c(.68,.32) ,replace = TRUE)
 hit_sum = sum(x =="Base")*.20
 out_sum = sum(x =="Out")
 return(hit_sum)
}



new = Player(70)
new

Это просто дает мне, сколько домашних прогонов из выборки 70. Будет ли цикл while как-то применяться к приведенному выше коду? Спасибо.

Ответы [ 4 ]

2 голосов
/ 27 марта 2019

Вот слегка измененная функция.

n_homerun <- function(N = 100, p_homerun = 0.2) {
    x <- sample(c("Base", "Out"), N, replace = TRUE, prob = c(0.32, 0.68))

    maxN <- which(cumsum(x == "Out") == 40)[1]
    if (length(maxN) == 0)
        stop("Sample has less than 40 Out's, increase N.")

    round(sum(x[1:maxN] == "Base") * p_homerun)
}

Теперь мы можем использовать replicate для генерации эмпирического распределения домашних прогонов

Nrep <- 10000
res <- replicate(Nrep, n_homerun(), simplify = TRUE)

Давайте построим график распределения

library(tidyverse)
data.frame(res = res) %>%
    count(res) %>%
    mutate(freq = n / Nrep) %>%
    ggplot(aes(res, freq)) +
    geom_col() +
    scale_x_continuous(breaks = 1:10)

enter image description here

0 голосов
/ 08 апреля 2019
 #Updating my prior respose, I'm sure you want a random number of runs per inning, 
 #based on probability.  I found this program for half an inning, 
 #https://gist.github.com/bayesball/36fba464d294944268f09630aa65ab61
 #I replaced "prob" line with 
prob <- c(27,0,0,0,0,4.3)   # inputs  in parenthesis are (outs, bases on 
 #balls, singles, doubles, triples, home runs) 

#I added the following to the online 1/2 inning program

st <- runs_setup()
R <- replicate(99999, simulate_half_inning(st))  # for complete 9 inning game make 
#number in parenthesis divisible by 9.  I picked 99999
round(prop.table(table(R)), 6)


b<-matrix(R,11111,9)   # this divides the 99999 random innings into 11111 games
hrteam<-apply(b,1,sum)
round(prop.table(table(hrteam)),6)

graph<-round(prop.table(table(hrteam)),6)
0 голосов
/ 08 апреля 2019
#I am also new with "R".   Browsing the internet, I came across this paper by Cal 
#Morris.

# http://www.stat.harvard.edu/People/Faculty/Carl_N._Morris/Carl_N._Morris_Sports_Articles/Runs_per_Game_Paper_(Short%20Version).txt

#I was trying to compute the game by hand, then realized I could make an "R"  
#program.

#Here it is
#######################
#Walking Team*
H=0
D=0
T=0
HR=0
SAC=0
BB=20.33383331
AB=27
PA= AB + BB

OBA=(H+BB)/PA




PA= AB + BB

P0= (1-OBA)^3
P1=3*OBA*(1-OBA)^3
P2=6*OBA^2*(1-OBA)^3
P3=1-P1-P2


hr =HR/(H +BB)
w= BB/(H +BB)
d= D/(H +BB)
t=T/(H +BB)
s=1-hr-w-d-t
d1= .576*d
d2=.424d
s1=.324*s
s2=.412*s
s3=.264*s
L1= 1-hr
L2=L1*w +(w+s)*(s + d1) +d*s1
L3= L2*w +((w+s)*(w+s1+s2) +d*w)*s1
LOB =(1-P0)*L1 +(1-P0-P1)*L2+(1-P0-P1-P2)*L3

Eruns=3*OBA/(1-OBA) 
9*(Eruns-LOB)          #averages 4.5 runs per game.

#Just play around with singles, doubles, triples, HRs to get the number of runs per 
#game you want. 31.5 at bats, 4.5 home runs per game, the rest outs will also get you 
#4.5 runs #per game, or 10.003816 singles, everything else zero will get 4.5 runs per 
#game. 
0 голосов
/ 27 марта 2019

Вы можете поднастроить свои x, когда в образце будет достигнуто 40 "Аутов".Попробуйте изменить свою функцию на

Player = function(n) {
    x = sample(c("Out","Base"), n , prob = c(.68,.32) ,replace = TRUE)
    inds <- cumsum(x == "Out") >= 40
    if (any(inds)) 
      x <- x[1:which.max(inds)]
    hit_sum = sum(x =="Base")*.20
    out_sum = sum(x =="Out")
    return(hit_sum)
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...