按行名和列名访问矩阵,如果不可用,则返回零 [英] 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"]
当我键入a ["x","z"]时,它给我一个错误"a [" x," z]中的错误:下标超出范围",应该是.
When I type a["x","z"], it gives me an error "Error in a["x", "z"] : subscript out of bounds", which should be.
我的问题是我怎么能得到零而不是那个错误.更确切地说,当我键入错误的行名或不在行名(a)或colnames(a)中的列名时,它将返回一个固定值,例如零.例如,对于a ["x","z"],a ["z","t"],...,为零.
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"], ... .
推荐答案
将其包装在tryCatch
中.不使用任何软件包:
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
这篇关于按行名和列名访问矩阵,如果不可用,则返回零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!