Reputation: 1
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:
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));
s0<-c(1,0,0,0)
mcHIV<-new("markovchain", states=state,byrow=T,transitionMatrix=tp,name="HIV")
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
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
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