简体   繁体   English

R:运行马尔可夫链模拟时出现的概率数错误

[英]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; 这是从“用R分析棒球数据”的第9章开始的,它试图模拟半局得分。

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)) 游程<-replicate(10000,模拟(tmatrix,R))

Error in sample.int(length(x), size, replace, prob) : incorrect number of probabilities sample.int(长度(x),大小,替换,概率)中的错误:概率数不正确

Clicking on "rerun with debug" in Rstudio points out the following line; 单击Rstudio中的“使用调试重新运行”会指出以下行;

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, .... 在您的代码中, s取1到25之间的任何值sample(1:25, ....

Hence, in order for P[s,] to work, it needs (at least) 25 rows. 因此,为了使P[s,]工作,它需要(至少)25行。 You pass this matrix to the simulate function. 您将此矩阵传递给simulate函数。 Hence, check it's dimensions 因此,请检查尺寸

dim(tmatrix)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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