[R] xtable with conditional formatting using \textcolor
Marc Schwartz
marc_schwartz at me.com
Wed Jun 1 20:47:26 CEST 2011
On Jun 1, 2011, at 1:33 PM, Walmes Zeviani wrote:
> Hello list,
>
> I'm doing a table with scores and I want include colors to represent status
> of an individual. I'm using sweave <<results=tex>>= and xtable but I can't
> get a result I want. My attemps are
>
> #-----------------------------------------------------------------------------
> # code R
>
> da <- data.frame(id=letters[1:5], score=1:5*2)
>
> col <- function(x){
> ifelse(x>7,
> paste("\textcolor{blue}{", formatC(x, dig=2, format="f"), "}"),
> paste("\textcolor{red}{", formatC(x, dig=2, format="f"), "}"))
> }
>
> da$score.string <- col(da$score)
>
> require(xtable)
> xtable(da[,c("id","score.string")])
>
> #-----------------------------------------------------------------------------
>
> actual result
> #-----------------------------------------------------------------------------
> \begin{tabular}{rll}
> \hline
> & id & score.string \\
> \hline
> 1 & a & extcolor\{red\}\{ 2.00 \} \\
> 2 & b & extcolor\{red\}\{ 4.00 \} \\
> 3 & c & extcolor\{red\}\{ 6.00 \} \\
> 4 & d & extcolor\{blue\}\{ 8.00 \} \\
> 5 & e & extcolor\{blue\}\{ 10.00 \} \\
> \hline
> \end{tabular}
> #-----------------------------------------------------------------------------
>
> desired result (lines omited to save space)
> #-----------------------------------------------------------------------------
> 1 & a & \textcolor{red}{ 2.00 } \\
> 2 & b & \textcolor{red}{ 4.00} \\
> #-----------------------------------------------------------------------------
>
> Any contribution will be useful. Thanks.
> Walmes.
When the '\t' is being cat()'d to the TeX file (or console) by print.xtable(), it is being interpreted as a tab character. You need to escape it with additional backslashes and then adjust the sanitize.text.function in print.xtable() so that it does not touch the backslashes:
da <- data.frame(id=letters[1:5], score=1:5*2)
col <- function(x){
ifelse(x>7,
paste("\\textcolor{blue}{", formatC(x, dig=2, format="f"), "}"),
paste("\\textcolor{red}{", formatC(x, dig=2, format="f"), "}"))
}
da$score.string <- col(da$score)
> da
id score score.string
1 a 2 \\textcolor{red}{ 2.00 }
2 b 4 \\textcolor{red}{ 4.00 }
3 c 6 \\textcolor{red}{ 6.00 }
4 d 8 \\textcolor{blue}{ 8.00 }
5 e 10 \\textcolor{blue}{ 10.00 }
require(xtable)
print(xtable(da[,c("id","score.string")]), sanitize.text.function = function(x){x})
That will give you:
% latex table generated in R 2.13.0 by xtable 1.5-6 package
% Wed Jun 1 13:44:54 2011
\begin{table}[ht]
\begin{center}
\begin{tabular}{rll}
\hline
& id & score.string \\
\hline
1 & a & \textcolor{red}{ 2.00 } \\
2 & b & \textcolor{red}{ 4.00 } \\
3 & c & \textcolor{red}{ 6.00 } \\
4 & d & \textcolor{blue}{ 8.00 } \\
5 & e & \textcolor{blue}{ 10.00 } \\
\hline
\end{tabular}
\end{center}
\end{table}
HTH,
Marc Schwartz
More information about the R-help
mailing list