9

我有要隐藏的 NA 和零的对角矩阵。

na.print = "" 工作正常,但 zero.print = "." 似乎将 0.00 视为 != 0 ?

这是一个带有打印输出的可运行示例,因此您可以了解我的意思:

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

遵循下面的有用答案(谢谢大家!),并基于 print.table 中的明确选择,而不是 zero.print 表中任何项目失败的项目(x == round(x)),这是一个适用于的版本浮点。我为数据框打印任务编写了它,但它适用于矩阵。

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")
4

2 回答 2

4

这是一种解决方法:

> print.table(local({x[x==0] <- NA; x}))
     [,1]  [,2] [,3]  [,4]
[1,]  0.01                
[2,]                      
[3,]            -0.01     
[4,]                      

如果您需要 NA 和零的不同表达式,那么,

> print(ifelse(is.na(x), "", ifelse(x == 0, ".", x)), quote = FALSE)
     [,1] [,2] [,3]  [,4]
[1,] 0.01                
[2,] .    .              
[3,] .    .    -0.01     
[4,] .    .    .     .  
于 2012-07-31T12:52:41.387 回答
3

根据 Andrie 的意见和建议,这不是print.table. 提供一个print.table期望table. 正如安德烈指出的那样,所有的赌注都与预期的输出有关。如果您添加一行额外的代码print.table(见下文),它将为您工作(注意我称之为 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 = ".")
于 2012-07-31T13:28:26.530 回答