实际上有两个不同的问题。第一个是如何显示零。通过查找 dispatch 后使用的确切方法很容易解决:
Matrix::printSpMatrix(toy, zero.print="0")
[1,] 0 0 0
[2,] 1 1 1
[3,] NA NA NA
第二个问题是NA 输出是否可以用其他字符来抑制。好吧,这不是直接可能的:没有合适的参数。
但是,修改源代码始终是一种选择。请注意:这是一种黑客攻击,可能会导致无法预料的后果!
toy_print <- function (x, digits = NULL, maxp = getOption("max.print"), cld = getClassDef(class(x)),
zero.print = ".", col.names, note.dropping.colnames = TRUE,
col.trailer = "", align = c("fancy", "right"))
{
stopifnot(extends(cld, "sparseMatrix"))
x.orig <- x
cx <- formatSpMatrix(x, digits = digits, maxp = maxp, cld = cld,
zero.print = zero.print, col.names = col.names, note.dropping.colnames = note.dropping.colnames,
align = align)
if (col.trailer != "")
cx <- cbind(cx, col.trailer, deparse.level = 0)
# here's the NA hack
cx[cx=="NA"] <- "."
print(cx, quote = FALSE, right = TRUE, max = maxp)
invisible(x.orig)
}
toy_print(toy, zero.print="0")
[1,] 0 0 0
[2,] 1 1 1
[3,] . . .