# Tables: count occurrences of a value in column

I have a big table made with tabular, in which each cell is either a "YES" or a "NO".

I would like to put at the bottom a "totals row", ie: a row that counts how many "YES" there are in each column and displays the total. Something like this:

Feature A | Y | N | Y |
Feature B | Y | Y | N |
Feature C | Y | N | Y |
Feature D | Y | N | Y |
TOTAL     | 4 | 1 | 3 |


Can this be done without having to manually count the occurrences? The table is big and subject to frequent changes, it would really be a pain to do it manually every time.

• This can be done with the collcell package with which you can check each entry of a column and step a counter and then add the value of this counter to the last row. – Peter Grill Jul 7 '15 at 9:22
• or you can wrap your cell content in a macro with a counter – musicman Jul 7 '15 at 9:26
• @musicman: this actually sounds more straightforward than using collcell, but is there a way to get the current column index from within a "cell"? Otherwise I would've to use a different macro for each column, which becomes cumbersome. – Master_T Jul 7 '15 at 10:02
• I don't think so. You would have to wrap each cell in the right command \countA{Y} & \countB{N} .... collcell seems to be the easier way – musicman Jul 7 '15 at 10:25

Using the collcell package you check each entry and step a counter to keep track of the total and at the end output the value of the counter.

## Notes:

• With some additional logic one should be able expand it so that there is only one column type, but to keep this simple I defined three separate column types.

## Code:

\documentclass{article}

\usepackage{collcell}
\usepackage{xstring}
\usepackage{array}

\newcounter{ColumnOne}
\newcounter{ColumnTwo}
\newcounter{ColumnThree}

\newcommand*{\CountColumnOne}[1]{%
\IfStrEq{#1}{Y}{\stepcounter{ColumnOne}}{}#1%
}
\newcommand*{\CountColumnTwo}[1]{%
\IfStrEq{#1}{Y}{\stepcounter{ColumnTwo}}{}#1%
}
\newcommand*{\CountColumnThree}[1]{%
\IfStrEq{#1}{Y}{\stepcounter{ColumnThree}}{}#1%
}
\newcolumntype{X}{>{\collectcell\CountColumnOne}{c}<{\endcollectcell}}
\newcolumntype{Y}{>{\collectcell\CountColumnTwo}{c}<{\endcollectcell}}
\newcolumntype{Z}{>{\collectcell\CountColumnThree}{c}<{\endcollectcell}}

\begin{document}
\begin{tabular}{l X Y Z}
Feature A & Y & N & Y \\
Feature B & Y & Y & N \\
Feature C & Y & N & Y \\
Feature D & Y & N & Y \\
TOTAL     & \arabic{ColumnOne} & \arabic{ColumnTwo} & \arabic{ColumnThree} \\
\end{tabular}
\end{document}