[R] Code for generating states and observations for HMM

Rolf Turner r.turner at auckland.ac.nz
Wed Jun 4 00:32:02 CEST 2014


You might find it helpful to look at the sim.hmm() function in the 
"hmm.discnp" package, or the simHMM() function in the "HMM" package.

cheers,

Rolf Turner

On 03/06/14 21:17, Bukar Alhaji wrote:
> Dear R buddies,
>
> Sorry for this silly question but am new to R. I am trying to
> generate states and observations to be use for Bayesian Hidden Markov
> Models analysis where i intend using mixture of Poisson and Negative
> binomial as emulsion. I use the code below to generate states and
> observations for homogeneous HMM . I would like to know if i
> correctly generated the data.
>
>
> pii = c(0.6,0.4)
> p1 <- matrix(c(0.8,0.2,0.3,0.7),byrow=TRUE,nrow=2)
>
>
>      NUM = 200
>      theta<-rep(0, NUM)
>      x<-rep(0, NUM)
>
>      ## generating the states
>      # initial state
>      theta[1]<-rbinom(1, 1, pii[1])
>      # other states
>      for (i in 2:NUM)
>      {
>        if (theta[i-1]==0)
>          theta[i]<-rbinom(1, 1, p1[1, 1])
>        else
>          theta[i]<-rbinom(1, 1, p1[2, 1])
>      }
>
>      ## generating the observations
>
>      for (i in 1:NUM)
>      {
>        if (theta[i]==0)
>        {
>          x[i]<-rpois(1, 5)
>        }
>        else
>        {
>          x[i]<-rnbinom(1, 3, 0.3)
>        }
>      }
>      data<-list(s=theta, o=x, p1 = p1, pii = pii)



More information about the R-help mailing list