On Jan 25, 2011, at 9:34 AM, Robin Hankin wrote:
> Hi.
>
> I'm writing a print method for an object that includes a numeric matrix
> for which
> the lower diagonal elements are not meaningful. So I make the lower
> diagonal of my matrix NA and print it.
>
> But my co-author does not like NA there and wants a dash.
>
> I have tried coercing the matrix to character, essentially by
> M[is.na(M)] <- "-" but this interferes with the pleasing
> column alignment for numerical matrices.
>
> How do I make R print "-" instead of "NA" for NA
entries in a numeric
> matrix, without altering the vertical alignment? Is there such a command
> as
>
> options(NA_string = "-")
>
> available?
>
> best wishes
>
> Robin Hankin
Robin,
How about this:
set.seed(1)
mat <- matrix(rnorm(16), 4, 4, )
> mat
[,1] [,2] [,3] [,4]
[1,] -0.6264538 0.3295078 0.5757814 -0.62124058
[2,] 0.1836433 -0.8204684 -0.3053884 -2.21469989
[3,] -0.8356286 0.4874291 1.5117812 1.12493092
[4,] 1.5952808 0.7383247 0.3898432 -0.04493361
mat[lower.tri(mat, diag = TRUE)] <- NA
> mat
[,1] [,2] [,3] [,4]
[1,] NA 0.3295078 0.5757814 -0.6212406
[2,] NA NA -0.3053884 -2.2146999
[3,] NA NA NA 1.1249309
[4,] NA NA NA NA
> print.table(mat, na.print = "-")
[,1] [,2] [,3] [,4]
[1,] - 0.3295078 0.5757814 -0.6212406
[2,] - - -0.3053884 -2.2146999
[3,] - - - 1.1249309
[4,] - - - -
See the 'na.print' argument in ?print.table
HTH,
Marc Schwartz