Reputation: 5
I want to calculate square de-normalized (= frequencies) transition matrix between state p(=previous) and n(=next). I have tried following script:
p <- c("S1", "S1", "S2", "S3", "S4")
n <- c("S2", "S2", "S3", "S4", "S5")
d <- data.frame(fprev=p, fnext=n)
counts <- table( as.data.frame( d ))
counts is following:
fnext
fprev S2 S3 S4 S5
S1 2 0 0 0
S2 0 1 0 0
S3 0 0 1 0
S4 0 0 0 1
This is quite close what I am wanting but I would like to get similar structure except that values for both fnext and fprev would be S1 S2 S3 S4 S5 (I have tried dnn parameter to table and deparse.level but they did not seem to help)
So expected output should have S1 S2 S3 S4 S5 in both column and row directions (naturally some more values 0 as for example there is no S5 state in fprev)
Upvotes: 0
Views: 251
Reputation: 1446
In order to get zeroes for all levels in your table you should set fprev
and fnext
to be factors with the same levels like so
p <- c("S1", "S1", "S2", "S3", "S4")
n <- c("S2", "S2", "S3", "S4", "S5")
lvls <- sort(unique(c(p, n)))
d <- data.frame(
fprev = factor(p, levels=lvls),
fnext = factor(n, levels=lvls)
)
counts <- table(d)
Now your counts
table should be how you want it.
fprev S1 S2 S3 S4 S5
S1 0 2 0 0 0
S2 0 0 1 0 0
S3 0 0 0 1 0
S4 0 0 0 0 1
S5 0 0 0 0 0
Upvotes: 3