问题
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"], ... .
回答1:
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
回答2:
We can wrap with a tryCatch
or possibly
from purrr
to make this happen
library(purrr)
f1 <- possibly(function(mat, indx1, indx2) mat[indx1, indx2], otherwise = 0)
f1(a, 'x', 'z')
#[1] 0
f1(a, 'x', 'y')
#[1] 3
回答3:
You could use match
to make sure an NA
is returned instead:
a[match("x",rownames(a)), match("y",colnames(a))]
#[1] 3
a[match("x",rownames(a)), match("z",colnames(a))]
#[1] NA
来源:https://stackoverflow.com/questions/53366492/access-matrix-by-rownames-and-colnames-and-return-zero-if-not-available