Domanda

Say I have a knitr chunk such as this:

library(xtable)

<<>>=
x <- matrix(c(0, 1, 2, 0, 4, 5))
xtable(x)
@

Which yields the following LaTeX code (excerpt):

\hline
1 & 0,00 \\ 
2 & 1,00 \\ 
3 & 2,00 \\ 
4 & 0,00 \\ 
5 & 4,00 \\ 
6 & 5,00 \\ 
\hline

However, my actual table is larger (12 x 6) and has many zeros, which makes spotting non-zeros quite a task. I'd like to follow local table formatting guidelines, which recommend using hyphens for integer zeros (as opposed to zeros that result from approximation). In other words, I want my xtable() output to look like this:

\hline
1 & - \\ 
2 & 1,00 \\ 
3 & 2,00 \\ 
4 & - \\ 
5 & 4,00 \\ 
6 & 5,00 \\ 
\hline

How can I achieve this? I've looked into R options and knitr opts_chunk functions to no avail.

È stato utile?

Soluzione

If you don't (otherwise) have missing data in the matrix/table, then you can use xtable's ability to format NA to get the required result. Just change the 0's to NA and then use the NA.string option to print.xtable

tmp <- x
tmp[tmp==0] <- NA
print(xtable(tmp), NA.string = "-")

which gives

% latex table generated in R 3.0.1 by xtable 1.7-1 package
% Fri Sep 20 13:25:27 2013
\begin{table}[ht]
\centering
\begin{tabular}{rr}
  \hline
 & x \\ 
  \hline
1 & - \\ 
  2 & 1.00 \\ 
  3 & 2.00 \\ 
  4 & - \\ 
  5 & 4.00 \\ 
  6 & 5.00 \\ 
   \hline
\end{tabular}
\end{table}

You could even wrap this in a function to isolate the mapping of 0 to NA from any other analysis and make it clear that this is for output formatting only.

xtable0dash <- function(x, ...) {
  x[x==0] <- NA
  print(xtable(x, ...), NA.string = "-")
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top