Sun Synergus
Sun Synergus

Reputation: 1

R Markov chain output iteration

I am currently using markovchain package for my analysis.

I have (a,b,c,d) for states,

I need to output a dataset, which contains proportion of a,b,c,d at each iteration. my codes are:

1.define states and transition probabilities

library(markovchain)
state<-c("a", "b","c","d");
tp<-matrix(data=c(0.721, 0.202,0.067,0.010,0,0.581,0.407,0.012,0,0,0.75,0.25,0,0,0,1),byrow=T, nrow=4, dimnames=list(state,state));

2.define initial state and markov chain

s0<-c(1,0,0,0)
mcHIV<-new("markovchain", states=state,byrow=T,transitionMatrix=tp,name="HIV")

3.do 20 iterations I HAVE PROBLEMS HERE!!

sq1<-seq(1,20)
s<-NULL

for (n in 1:20){s[n]<-mcHIV^sq1[n]};

Error in s[n] <- mcHIV^sq1[n] : invalid type/length (S4/0) in vector allocation**

How shoud I handle this?

Upvotes: 0

Views: 588

Answers (2)

mlegge
mlegge

Reputation: 6913

Since the output is a matrix you need to create a list:

s <- list()
for (n in 1:20){s[[n]] <- mcHIV^sq1[n]};

Each element of the list, s[[1]], s[[2]], ..., s[[k]] will refer to the state of the transition matrix after iteration k

An better way to do this programmatically is to use lapply which returns a list of objects, in this case, the transition matrices:

iter <- 20
s <- lapply(seq(iter), function(k) mcHIV^k)

Still accessible by s[[1]], s[[2]], ..., s[[k]]

Upvotes: 1

Sidhha
Sidhha

Reputation: 268

for (n in 1:20){s<-c(s,mcHIV^sq1[n])};

You can create a list of matrices to store the desired result.

Upvotes: 0

Related Questions