【问题标题】:R: Incorrect number of probabilities error when running Markov Chain simulationR:运行马尔可夫链模拟时的概率错误数不正确
【发布时间】:2023-03-20 04:49:02
【问题描述】:

这来自“用 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
}

这与书中的代码几乎相同。当我尝试使用以下代码运行它时,出现以下错误;

运行

sample.int(length(x), size, replace, prob) 中的错误: 概率数不正确

在 Rstudio 中点击“rerun with debug”会指出以下行;

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

这是唯一有意义的事情,因为它与概率的数量有关。关于如何改变它的任何想法?

【问题讨论】:

    标签: r simulation markov-chains


    【解决方案1】:

    在您的代码中,s 取 1 到 25 之间的任何值 - sample(1:25, ....

    因此,为了让P[s,] 工作,它需要(至少)25 行。您将此矩阵传递给simulate 函数。因此,检查它的尺寸

    dim(tmatrix)
    

    【讨论】:

    • 嗯好吧,这是有道理的,我传递的矩阵的尺寸为 24 X 26。我在 while 和 s.new 语句中将函数值从 25 更改为 26。然而,这只会产生一个不同的错误:“R[s, s.new] 中的错误:下标越界”
    • @user3334415:发布一个可重复的示例,以便停止猜测并开始编码。
    猜你喜欢
    • 1970-01-01
    • 2018-03-25
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-24
    • 1970-01-01
    相关资源
    最近更新 更多