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 = "-")
}