简体   繁体   English

R中的马尔可夫链

[英]Markov chain in R

Suppose we have a ten state system where an observation can enter the system in any one of the ten states with equal probability and move from the given state into a new state also with equal probability (the observation's new state isn't conditional on its previous state and the observation can remain in its current state).假设我们有一个十状态系统,其中一个观察可以以等概率进入十个状态中的任何一个状态,并以等概率从给定状态移动到新状态(观察的新状态不取决于其先前的状态)状态并且观察可以保持在当前状态)。 Additionally, an individual can "die" within any of the given ten states at any time including its current state.此外,一个人可以在任何时间(包括其当前状态)在给定的十种状态中的任何一种内“死亡”。 How exactly could this be setup in R or is this not even possible in R?这究竟是如何在 R 中设置的,或者这在 R 中甚至是不可能的?

This sounds like a compartmental modelling problem.这听起来像是一个分区建模问题。 You could solve it with the SimInf package:你可以用SimInf包解决它:

library(SimInf)

Define names of your 10 compartments:定义 10 个隔间的名称:

compartments <- letters[1:10]

Define rates of enter and exit.定义进入和退出率。 In this case, as you suggested all enter events have the same rate to all compartments: k1 enter and k2 exit.在这种情况下,正如您所建议的,所有进入事件对所有隔间都具有相同的速率:k1 进入和 k2 退出。

enterexit <- unlist(lapply(compartments, function(x){
    c(paste0("@ -> k1 -> ", x), paste0(x, "-> k2*", x, " -> @"))
}))

Define transitions between compartments.定义隔间之间的过渡。 All get the same rate k3.都得到相同的速率 k3。 So the individuals can just bounce around all 10 compartments at an equal probability:因此,这些人可以以相等的概率在所有 10 个隔间中弹跳:

transitions <- unlist(lapply(1:10, function(x){
    unlist(lapply(compartments[-x], function(y){
        paste0(compartments[x], "-> k3*", compartments[x], "->", y)
    }))
}))

Now define the initial state of the compartments.现在定义隔间的初始状态。 I'm going to put 0 in all ten compartments;我要把 0 放在所有十个隔间里; you could also add some individuals to start if you wish:如果您愿意,您还可以添加一些人开始:

u0 <-  data.frame(a = 0,
                  b = 0,
                  c = 0,
                  d = 0,
                  e = 0,
                  f = 0,
                  g = 0,
                  h = 0,
                  i = 0,
                  j = 0)

define the number of time steps for the model to run:定义模型运行的时间步数:

tspan = 1:100

Initialize the model:初始化模型:

model <- mparse(transitions = c(enterexit, transitions),
                compartments = compartments,
                k1 = 0.5,
                k2 = 0.5,
                k3 = 0.5)
model <- init(model, u0, tspan)

Run the model运行模型

ob <- run(model)

Plot it绘制它

plot(ob, N = TRUE)

Get a dataframe of the number of units in each compartment at each time step在每个时间步获取每个隔间中单元数的数据框

df <- trajectory(ob)

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

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