I have diagonal matrices with NAs and zeros I want to hide.
na.print = "" is working fine, but zero.print = "." seems to treating 0.00 as != 0 ?
Here's a runnable example with print out so you can see what I mean:
x <- matrix(c(0.01, NA, NA, NA, 0.00, 0.00, NA, NA, 0.00, 0.00, -0.01, NA, 0.00, 0.00, 0.00, 0.00), nrow=4, byrow=TRUE)
x
[,1] [,2] [,3] [,4]
[1,] 0.01 NA NA NA
[2,] 0.00 0 NA NA
[3,] 0.00 0 -0.01 NA
[4,] 0.00 0 0.00 0
print.table(x, na.print="", zero.print=".")
[,1] [,2] [,3] [,4]
[1,] 0.01
[2,] 0.00 0.00
[3,] 0.00 0.00 -0.01
[4,] 0.00 0.00 0.00 0.00
Following the helpful answers below (thanks guys!), and based on the explicit choice in print.table to not zero.print items where any item in the table fails (x == round(x)), here's a version which works with floating.point. I wrote it for a dataframe printing task, but it works with matrices.
print.dataframe <- function (x, digits = getOption("digits"), quote = FALSE, na.print = "", zero.print = "0", justify = "none", ...){
xx <- format(x, digits = digits, justify = justify)
if (any(ina <- is.na(x)))
xx[ina] <- na.print
i0 <- !ina & x == 0
if (zero.print != "0" && any(i0))
xx[i0] <- zero.print
if (is.numeric(x) || is.complex(x)){
print(xx, quote = quote, right = TRUE, ...)
}else{
print(xx, quote = quote, ...)
}
invisible(x)
}
print.dataframe(bob, zero.print = ".", justify="left")
Here is a workaround:
> print.table(local({x[x==0] <- NA; x}))
[,1] [,2] [,3] [,4]
[1,] 0.01
[2,]
[3,] -0.01
[4,]
In the case that you need different expression for NA and zero, then,
> print(ifelse(is.na(x), "", ifelse(x == 0, ".", x)), quote = FALSE)
[,1] [,2] [,3] [,4]
[1,] 0.01
[2,] . .
[3,] . . -0.01
[4,] . . . .
Per Andrie's input and suggestion this is not a bug in the code with print.table
. It's a problem with supplying a matrix to print.table
which expects a table
. As Andrie points out all bets are off with the expected output. If you add one additional line of code to print.table
(seen below) it will work for you (note I called this printmatrix).
printmatrix <-
function (x, digits = getOption("digits"), quote = FALSE, na.print = "",
zero.print = "0", justify = "none", ...)
{
xx <- format(unclass(x), digits = digits, justify = justify)
if (any(ina <- is.na(x)))
xx[ina] <- na.print
if (zero.print != "0" && any(i0 <- !ina & x == 0) && all(x ==
round(x)))
xx[i0] <- sub("0", zero.print, xx[i0])
xx[x == 0] <- zero.print #the line I added
if (is.numeric(x) || is.complex(x))
print(xx, quote = quote, right = TRUE, ...)
else print(xx, quote = quote, ...)
invisible(x)
}
printmatrix(x, zero.print = ".")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With