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

repeat_pattern(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.

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

Author

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

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
#>  P( x0 )
#>  P( x1 | x0 )
#>  P( x2 | x1 )
#>  P( x3 | x2 )
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
#>  P( x0 )
#>  P( x1 | x0 )
#>  P( y1 | x1 )
#>  P( x2 | x1 )
#>  P( y2 | x2 )
#>  P( x3 | x2 )
#>  P( y3 | x3 )
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
#>  P( x0 )
#>  P( x1 | x0 )
#>  P( x2 | x1 )
#>  P( x3 | x2 )
#>  P( x4 | x2 )
#>  P( x5 | x3 )
#>  P( x6 | x3 )
#>  P( x7 | x4 )
#>  P( x8 | x4 )
tree <- tree |> grain()
tree 
#> Independence network: Compiled: TRUE Propagated: FALSE Evidence: FALSE