repeat_pattern: Create repeated patterns in Bayesian networks

View source: R/repeat_pattern.R

repeat_patternR Documentation

Create repeated patterns in Bayesian networks

Description

Repeated patterns is a useful model specification short cut for Bayesian networks

Usage

repeat_pattern(plist, instances, unlist = TRUE, data = NULL)

repeatPattern(plist, instances, unlist = TRUE, data = NULL)

Arguments

plist

A list of conditional probability tables. The variable names must have the form name[i] and the i will be substituted by the values given in instances below. See also the data argument.

instances

A vector of consecutive integers

unlist

If FALSE the result is a list in which each element is a copy of plist in which name[i] are substituted. If TRUE the result is the result of applying unlist().

data

A two column matrix. The first column is the index / name of a node; the second column is the index / name of the node's parent.

Author(s)

Søren Højsgaard, sorenh@math.aau.dk

References

Søren Højsgaard (2012). Graphical Independence Networks with the gRain Package for R. Journal of Statistical Software, 46(10), 1-26. https://www.jstatsoft.org/v46/i10/.

See Also

grain, compile_cpt

Examples


yn <- c("yes", "no")
n <- 3

## Example: Markov chain

x_init  <- cpt(~x0, values=c(1, 9), levels=yn)                  ## p(x0)
x_trans <- cpt(~x[i]|x[i-1], values=c(1, 99, 2, 98), levels=yn) ## p(x[i]|x[i-1])
pat     <- list(x_trans)                             
rep.pat <- repeat_pattern(pat, instances=1:n)

mc <- compile_cpt(c(list(x_init), rep.pat))
mc
mc <- mc |> grain()

## Example: Hidden markov model:
# The x[i]'s are unobserved, the y[i]'s can be observed.

x_init  <- cpt(~x0, values=c(1, 9), levels=yn)                   ##  p(x0)
x_trans <- cpt(~x[i]|x[i-1], values=c(1, 99, 2, 98), levels=yn)  ##  p(x[i]|x[i-1])
y_emis  <- cpt(~y[i]|x[i], values=c(10, 90, 20, 80), levels=yn)  ##  p(y[i]|x[i]) 

pat     <- list(x_trans, y_emis) ## Pattern to be repeated
rep.pat <- repeat_pattern(pat, instances=1:n)
hmm <- compile_cpt(c(list(x_init), rep.pat)) 
hmm
hmm <- hmm |> grain()

## Data-driven variable names

dep <- data.frame(i=c(1, 2, 3, 4, 5, 6, 7, 8),
                  p=c(0, 1, 2, 2, 3, 3, 4, 4))

x0 <- cpt(~x0, values=c(0.5, 0.5), levels=yn)
xa <- cpt(~x[i] | x[data[i, "p"]], values=c(1, 9, 2, 8), levels=yn)
xb <- repeat_pattern(list(xa), instances=1:nrow(dep), data=dep)
tree <- compile_cpt(c(list(x0), xb))
tree
tree <- tree |> grain()
tree 


gRain documentation built on Nov. 21, 2023, 5:07 p.m.