[Tex/LaTex] Color with Table Environment

colorfloatstables

Please have a look at the following code:

\documentclass[12pt]{report}
\usepackage[]{graphicx}
\usepackage[]{xcolor}
\usepackage{booktabs}

\begin{document}

\colorbox{yellow!20}{
\begin{table}
\begin{tabular}{lll}
\toprule
\multicolumn{1}{l}{}&\multicolumn{1}{c}{Female}&\multicolumn{1}{c}{Male}\tabularnewline                                   
\midrule
1 year- 2 years&2 (50\%)&2 (13.33\%)\tabularnewline
2 years - 3 years&0 (0\%)&4 (26.67\%)\tabularnewline
3 years +&1 (25\%)&3 (20\%)\tabularnewline
6 months- 1 year&1 (25\%)&3 (20\%)\tabularnewline
Less than 6 months&0 (0\%)&3 (20\%)\tabularnewline
\bottomrule
\end{tabular}
\end{table}
}

\end{document}

I don't get a output from the above code. But if comment out Table environment that is I put the Tabular environment in the colorbox then it works. My objective is to color the entire table but I want to color the Table environment. This is because I am creating table with latex function from Hmisc package from R which automatically creates the Table environment. I know I could use xtable package with floating=False option but I need to use latex function for other purposes.

I also understand I am not supposed to ask R questions here but since the latex related problem arose due to use of certain R package, if any one could suggest a workaround with R tables to created colored background in latex that would be quite helpful.

Best Answer

You cannot put a float such as table inside a \colorbox which is static. Go the other way around and use \colorbox inside table:

\documentclass[12pt]{report}
\usepackage[]{graphicx}
\usepackage[]{xcolor}
\usepackage{booktabs}

\begin{document}

\begin{table}
\colorbox{yellow!20}{%
\begin{tabular}{lll}
\toprule
\multicolumn{1}{l}{}&\multicolumn{1}{c}{Female}&\multicolumn{1}{c}{Male}\tabularnewline                                   
\midrule
1 year- 2 years&2 (50\%)&2 (13.33\%)\tabularnewline
2 years - 3 years&0 (0\%)&4 (26.67\%)\tabularnewline
3 years +&1 (25\%)&3 (20\%)\tabularnewline
6 months- 1 year&1 (25\%)&3 (20\%)\tabularnewline
Less than 6 months&0 (0\%)&3 (20\%)\tabularnewline
\bottomrule
\end{tabular}%
}
\end{table}

\end{document}

enter image description here

I'd suggest you to use siunitx to properly format and align your data.