1

谁能向我解释为什么此代码的分布:

InfectionHistory <- rep(1,100)
for(x in 1:99)
{
  r <- runif(1)
  print(r)
  if(InfectionHistory[x]==1)
  {
    if(r < 0.04)
    {
      InfectionHistory[x+1] <- 2
    }
    else
    {
      InfectionHistory[x+1] <- InfectionHistory[x]
    }
  }
  if(InfectionHistory[x]==2)
  {
    if(r < 0.11)
    {
      InfectionHistory[x+1] <- 1
    }
    else
    {
      InfectionHistory[x+1] <- InfectionHistory[x]
    }
  }
}
plot(InfectionHistory, xlab = "Day", ylab = "State", main = "Patient Status per Day", type = "o")

与此代码不同:

InfectionHistory <- rep(1,100)
for(x in 1:99)
{
  r <- runif(1)
  print(r)
  if((InfectionHistory[x]==1)&&(r < 0.04))
  {
    InfectionHistory[x+1] <- 2
  }
  if((InfectionHistory[x]==2)&&(r < 0.11))
  {
    InfectionHistory[x+1] <- 1 
  }
}
plot(InfectionHistory, xlab = "Day", ylab = "State", main = "Patient Status per Day", type = "o")

我觉得这与 if-else 语句的逻辑有关。代码的目标是模拟一个沿着马尔可夫链的感染模型

4

1 回答 1

0

第一个示例包含if else嵌套在if语句中的对。

第二个示例包含if具有复合条件的语句。

经过粗略的审查,看起来每个示例都应该做同样的事情。此代码作为示例,嵌套if语句可以重写为if具有复合条件的语句。

例如,在示例 1 中,当我们到达这行代码时:

if(r < 0.04)
{
  InfectionHistory[x+1] <- 2
}

我们已经知道

InfectionHistory[x]==1

已返回true,否则我们将不在if检查此条件的主体内。

在第二个例子中,这被简单地重写为:

if((InfectionHistory[x]==1)&&(r < 0.04))
{
    InfectionHistory[x+1] <- 2
}

编辑:再看一遍,第二个例子似乎没有处理案例:

else
{
  InfectionHistory[x+1] <- InfectionHistory[x]
}

在第一个示例中重复了这段代码。它与两个嵌套if语句配对。第二个例子可以很容易地重写来处理这个问题,但是if else if else结构很简单。例如:

if((InfectionHistory[x]==1)&&(r < 0.04))
{
    InfectionHistory[x+1] <- 2
}
else if((InfectionHistory[x]==2)&&(r < 0.11))
{
    InfectionHistory[x+1] <- 1 
}
else
{
    InfectionHistory[x+1] <- InfectionHistory[x]
}
于 2013-10-30T17:26:59.773 回答