Skip to content
Prev 261581 / 398502 Next

xtable with conditional formatting using \textcolor

On Jun 1, 2011, at 1:33 PM, Walmes Zeviani wrote:

            
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)
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