---
title: "Tables"
author: "Robin J. Evans"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Tables}
  %\VignetteEngine{knitr::rmarkdown}
  \usepackage[utf8]{inputenc}
---

This package contains methods for storing and manipulating collections of contingency 
tables, and for easily vectorizing functions which apply to a contingency table.  

The basis of this is the class of object `tables`, which contains a collection of 
numerical tables all of the same dimension.  Let's create a collection of 10 
contingency tables (in this case probability tables), each of dimension 2x2x2.
```{r}
library(contingency)
tab <- rprobMat(10, 2, 3)
tab
```
The print method shows the first table in the list.  
The tables are stored as a matrix as can be seen by using the `dim()` function.  Accessing
particular rows of this matrix return the appropriate tables:
```{r}
tab[c(1,4,5),]
```
However we can also specific elements of the tables using their co-ordinates, and 
(optionally) leaving the first entry blank:
```{r}
tab[,1,1,]
```
The `drop` argument can be set to `FALSE` if dimensions
of length 1 should be retained:
```{r}
tab[,1,1,,drop=FALSE]
```

## Basic Manipulations

Some basic operations are predefined, such as taking the margin of each table, or 
calculating a conditional distribution.
```{r}
margin(tab, 2:3)         # margin of second and third dimensions
conditional(tab, 2, 1)  # second dimension conditional on first
```
These can also be applied on an ordinary numerical array 
with the expected effect.
It can also be useful to calcuate conditional or 
other functions but retain the placement of values 
in the same point as the original table.  For this 
purpose the functions `margin2()` and `conditional2()` are
available.
```{r}
                         # as above but sequence of cells
margin2(tab, 2:3)        # in table is retained
conditional2(tab, 2, 1)  
```

## Functions of Distributions

Some built-in functions are available.  For example:
```{r}
tab2 <- rprobMat(10,2,3)
kl(tab, tab2)   # pairwise Kullback-Leibler divergence
                       # mutual information between
mutualInf(tab, 2, 3)   # second and third dimensions
mutualInf(tab, 2, 3, cond=1)   # conditional mutual information
```

<!-- ## Graphical Models -->

<!-- Using the `MixedGraphs` package, one can generate  -->
<!-- distributions satisfying the Markov properties of -->
<!-- a directed acyclic graph.  For example: -->
<!-- ```{r} -->
<!-- library(MixedGraphs) -->
<!-- dag1 <- graphCr("1 -> 3 <- 2") -->
<!-- tab3 <- rDAGmodel(dag1, 10) -->
<!-- ``` -->
<!-- Now the graph implies that the first -->
<!-- and second margins are independent.  We can use  -->
<!-- `checkCI()` to confirm this.  By default it uses -->
<!-- machine precision. -->
<!-- ```{r} -->
<!-- checkCI(tab3, 1, 2)  # should be TRUE -->
<!-- checkCI(tab3, 1, 3)  # FALSE with very high prob. -->
<!-- ``` -->


