简体   繁体   中英

R: Incorrect number of probabilities error when running Markov Chain simulation

This is from chapter 9 of "Analyzing Baseball Data with R," attempting to simulate runs scored in a half inning;

simulate<-function(P,R,start=1){
s<-start; path<-NULL; runs<-0
while(s<25){
s.new<-sample(1:25, 1, prob=P[s, ])
path<-c(path, s.new)
runs<-runs + R[s, s.new]
s<-s.new
}
runs
}

this is pretty much identical to the code in the book. When I attempt to run it with the following code, I get the following error;

RUNS<-replicate(10000,simulate(tmatrix,R))

Error in sample.int(length(x), size, replace, prob) : incorrect number of probabilities

Clicking on "rerun with debug" in Rstudio points out the following line;

s.new<-sample(1:25, 1, prob=P[s, ])

Which is the only thing that makes sense here since it has an issue with the number of probabilities. Any ideas on how to alter this?

In your code, s takes any value between 1 and 25 - sample(1:25, ....

Hence, in order for P[s,] to work, it needs (at least) 25 rows. You pass this matrix to the simulate function. Hence, check it's dimensions

dim(tmatrix)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM