[Tex/LaTex] How to do simple calculation in latex tables

calculationstables

Here I wish to do three things:

1) I want my table to be like this one below

enter image description here

whereas mine is

enter image description here

2) I want numbers to appear in the same format as their heading p (in bold)

3) I want latex to do some calculation. p in my table represents the proportion of females (females/(males + females)). I am wondering whether latex can do that for me because I have 16 groups and don't wan to calculate each?

% !TEX encoding = UTF-8 Unicode
\documentclass[a4paper,12pt]{report}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[turkish]{babel}
\usepackage{amsmath}
\usepackage{amssymb}

\begin{document}

\begin{table}[h!]
\centering
\begin{tabular}{c|c|c|r} 

Group No & Females  & Males & \textbf{p} \\ \hline
1 & 18 & 11 &  \\
2 & 31 & 22 &  \\
3 & 34 & 27 &  \\
4 & 33 & 29 &  \\
5 & 27 & 24 &  \\
6 & 33 & 29 &  \\
7 & 28 & 25 &  \\
8 & 23 & 26 &  \\
9 & 33 & 38 &  \\
10 & 12 & 14 &  \\
11 & 19 & 23 &  \\
12 & 25 & 31 &  \\
13 & 14 & 20 &  \\
14 & 2 & 20 &  \\
15 & 22 & 6 &  \\
16 & 7 & 34 &  \\
\end{tabular}
\end{table}
\end{document}

Best Answer

Here's a solution with collcell and xparse (for \fp_eval:n)

\documentclass{article}
\usepackage{collcell,booktabs,siunitx}
\usepackage{xparse}

\newcolumntype{F}{>{\collectcell\rememberF}c<{\endcollectcell}}
\newcolumntype{M}{>{\collectcell\rememberM}c<{\endcollectcell}}
\newcolumntype{P}{>{\collectcell\computeP}r<{\endcollectcell}}

\newcommand{\rememberF}[1]{%
  \gdef\FEMALE{#1}#1%
}
\newcommand{\rememberM}[1]{%
  \gdef\MALE{#1}#1%
}

\ExplSyntaxOn
\NewDocumentCommand{\computeP}{}
 {
  \bfseries\fp_eval:n { round ( \FEMALE/(\FEMALE+\MALE) , 2 ) }
 }
\ExplSyntaxOff

\begin{document}

\begin{tabular}{c F M P}
\toprule
Group No &
  \multicolumn{1}{c}{Females} &
  \multicolumn{1}{c}{Males} &
  \multicolumn{1}{c}{\textbf{p}} \\
\midrule
1 & 18 & 11 &  \\
2 & 31 & 22 &  \\
3 & 34 & 27 &  \\
4 & 33 & 29 &  \\
5 & 27 & 24 &  \\
6 & 33 & 29 &  \\
7 & 28 & 25 &  \\
8 & 23 & 26 &  \\
9 & 33 & 38 &  \\
10 & 12 & 14 &  \\
11 & 19 & 23 &  \\
12 & 25 & 31 &  \\
13 & 14 & 20 &  \\
14 & 2 & 20 &  \\
15 & 22 & 6 &  \\
16 & 7 & 34 &  \\
\bottomrule
\end{tabular}

\end{document}

Usage of booktabs features is not mandatory, but the table layout is better without vertical rules.

enter image description here

The F and M column types remember the entry in \FEMALE and \MALE respectively and print them, the P column type computes the ratio and prints it. In the first row it's necessary to use \multicolumn so as to avoid these macros to kick in.

The number of decimal digits can be changed in the \computeP macro, the value I used is 2.