R中是否存在使用稀疏转移矩阵生成马尔可夫链的函数?

时间:2016-09-20 18:19:22

标签: r sparse-matrix markov-chains

我有一个稀疏转换矩阵(更具体地说是类dgCMatrix的对象,它是在 Matrix 包中定义的类,其rowSums总是等于1)并且我想使用它作为生成马尔可夫链的转移矩阵。

是否有人知道使用该对象作为转移矩阵对离散马尔可夫链进行采样的函数(在任何包中或用户构建中)?

我已经查看了 markovchain 包,但对于该包中的函数,似乎需要一个传统的(密集)矩阵。

由于

编辑:这是我快速而又肮脏的解决方案:

simulate <- function(TransMat,N) {

  # idx is in 1:length(TransMat@Dimnames[[1]]), 
  # while the values in TransMat@i are in 0:(length(TransMat@Dimnames[[1]]) - 1)

  transition <- function(idx,TransMat) {
    # Returns the index (in 1:length(TransMat@Dimnames[[1]])) of the next state,
    # randomly sampled according to the idx-th row of the transition matrix TransMat.

    # Discrete variable sampling
    u = runif(1)                                       
    cs = cumsum(TransMat@x[(TransMat@i + 1) == idx])   
    # Position of the sampled value inside the vector of indices with value equal to idx, TransMat@i[(TransMat@i + 1) == idx]
    # which(cs > u)[1]
    # Position of the sampled value inside whole the vector of indices, TransMat@i
    # which((TransMat@i + 1) == idx)[which(cs > u)[1]]
    which(TransMat@p >= which((TransMat@i + 1) == idx)[which(cs > u)[1]])[1] - 1
  }

  sim <- integer(N)
  # The initial state is fixed
  sim[1] <- 1
  # The initial state is randomly distributed according to a given (discrete) initial distribution:
  # TO BE DONE
  for (i in 2:N) 
    sim[i] <- transition(sim[i-1], TransMat)

  sim
}

0 个答案:

没有答案