Search code examples
rmatrixzero

access matrix by rownames and colnames, and return zero if not available


I have a matrix with rownames and colnames as:

a = matrix(1:4,2,2)
dimnames(a) = list(c("x","y"),c("x","y"))

I can have access to matrix elements by rownames and colnames, for example,

a["x","y"]

When I type a["x","z"], it gives me an error "Error in a["x", "z"] : subscript out of bounds", which should be.

My question is how can I get zero instead of that error. More precisely, when I type wrong rownames or colnames that are not in rownames(a) or colnames(a), it returns a fixed value such as zero. For example, zero for a["x","z"], a["z","t"], ... .


Solution

  • Wrap it in tryCatch. No packages are used:

    tryCatch(a["x", "y"], error = function(e) 0)
    ## [1] 3
    
    tryCatch(a["x", "w"], error = function(e) 0)
    ## [1] 0