## Example: Markov chain
yn <- c("yes", "no")
## Specify p(x0)
x.0 <- cptable(~x0, values=c(1, 9), levels=yn)
## Specify transition density
x.x <- cptable(~x[i]|x[i-1], values=c(1, 99, 2, 98), levels=yn)
## Pattern to be repeated
pat <- list(x.x)
rep.pat <- repeatPattern(pat, instances=1:5)
cpt <- compileCPT(c(list(x.0), rep.pat))
mc <- grain(cpt)
if (interactive()) iplot(mc)
## Example: Hidden markov model: The x[i]'s are unobserved, the
## y[i]'s can be observed.
yn <- c("yes", "no")
## Specify p(x0)
x.0 <- cptable(~x0, values=c(1, 9), levels=yn)
## Specify transition density
x.x <- cptable(~x[i]|x[i-1], values=c(1, 99, 2, 98), levels=yn)
## Specify emission density
y.x <- cptable(~y[i]|x[i], values=c(10, 90, 20, 80), levels=yn)
## The pattern to be repeated
pat <- list(x.x, y.x)
## Repeat pattern and create network
rep.pat <- repeatPattern(pat, instances=1:5)
cpt <- compileCPT(c(list(x.0), rep.pat))
hmm <- grain(cpt)
hmm
if (interactive()) iplot(hmm)
## Data-driven variable names
x0 <- cptable(~x0, values=c(0.5, 0.5), levels=yn)
x <- cptable(~x[i] | x[data[i, "p"]], values=c(0.5, 0.5), levels=yn)
dep <- data.frame(i=c(1, 2, 3, 4, 5, 6, 7, 8),
p=c(0, 1, 2, 2, 3, 3, 4, 4))
x <- repeatPattern(list(x), instances=dep$i, data=dep)
tree <- compileCPT(c(list(x0), x))
tree <- grain(tree)
tree
if (interactive()) iplot(tree)
Run the code above in your browser using DataLab