简体   繁体   中英

How do I set the replaced value in a sparse matrix to NA rather than 0?

I would like to use sparse matrices for an analysis. Each cell in the sparse matrix comprises one value from the set {0,1,NA}. NA here represents a missing value.

For example, I can use the following code to create a sparse matrix:

    library(Matrix); 
    toy <- Matrix(c(0,1,NA), nrow=3, ncol=3, sparse = TRUE)

and I get the following output:

.  .  .
1  1  1
NA NA NA

Is it possible to use the Matrix function to create a function in which the datapoints 'left out' of the matrix are the NA values rather than 0? Are there other functions that I could use?

Therefore, from my example, my desired output is:

0 0 0
1 1 1
. . .

I have explored help pages and websites but I haven't found the answer. I believe I need to set the 'replValue'.

There are two separate questions, actually. The first one is how to display zeroes. It is easy to solve by looking for the exact method that is used after dispatch:

Matrix::printSpMatrix(toy, zero.print="0")

[1,]  0  0  0
[2,]  1  1  1
[3,] NA NA NA

The second question is whether the NA output can be suppressed with some other character. Well, it is not directly possible: there is no suitable parameter for that.

However, modifying the source is always an option. Beware: this is a hack, which may lead to unforseen consequences!

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,]  .  .  .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM