野球1イニングあたりの得点確率

避難所

Nout<- 3
Nbase<- 4
Nbatter<- 13
Bprob<- c(0.7,0.1,0.1,0.05,0.05)
#Ninning<- 9
#Bprob<- c(0.85,0.05,0.08,0.02)

#To count each batting pattern from 1 to Nbase.
num.count<- function(vec){
  counter<- rep(0,Nbase)
  for(result in 1:Nbase){
    counter[result]<- length(which(vec==result))
  }
  return(c(Nout,counter))
}
#The result contains zero(length is Nbase+1).

#To count the one inning scores of each sequence.
score<- function(vec){
  runner<- rep(0,Nbase)
  for(k in 1:length(vec)){
      runner<- c(runner,c(1,rep(0,(vec[k] - 1))))
  }
  runner<- runner[1:(length(runner) - (Nbase - 1))]
  #runner<- runner[-c((length(seq) - Nbase + 1):length(seq))]
  return(sum(runner))
}

#To count the probability to get a certain score by given sequence.
Prob<- function(vec){
  P<- choose((Nout+length(vec)-1),(Nout-1))*prod((Bprob^num.count(vec)))
  return(c(score(vec),P))
}

Result<- rep(0,(Nbatter-Nout+1))
  a<- p<- list(c(1:Nbase))
  Bpatterns<- expand.grid(p)
  PROBABILITY<- apply(Bpatterns,1,Prob)
  for(w in 0:max(PROBABILITY)){
    Result[w+1]<- Result[w+1]+sum(PROBABILITY[2,which(PROBABILITY[1,]==w)])
  }
for(b in 1:(Nbatter-Nout-1)){
  p<- c(p,a)
  Bpatterns<- expand.grid(p)
  PROBABILITY<- apply(Bpatterns,1,Prob)
  for(w in 0:max(PROBABILITY)){
    Result[w+1]<- Result[w+1]+sum(PROBABILITY[2,which(PROBABILITY[1,]==w)])
  }
}
Result[1]<- Result[1]+Bprob[1]^Nout
Result
sum(Result)

 Result
 [1] 6.654200e-01 1.730435e-01 9.017127e-02 4.171772e-02 1.787188e-02 7.255530e-03
 [7] 2.830949e-03 1.071401e-03 3.940491e-04 1.287242e-04 2.227919e-05