简体   繁体   English

按行名和列名访问矩阵,如果不可用,则返回零

[英]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. 当我键入a [“ x”,“ z”]时,它给我一个错误“ a [” x“,” z“]中的错误:下标超出范围”,应该是。

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. 更确切地说,当我键入错误的行名或不在行名(a)或colnames(a)中的列名时,它将返回一个固定值,例如零。 For example, zero for a["x","z"], a["z","t"], ... . 例如,对于a [“ x”,“ z”],a [“ z”,“ t”],...为零。

Wrap it in tryCatch . 将其包装在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

We can wrap with a tryCatch or possibly from purrr to make this happen 我们可以用tryCatchpossiblypurrr来实现

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

You could use match to make sure an NA is returned instead: 您可以使用match来确保返回NA

a[match("x",rownames(a)), match("y",colnames(a))]
#[1] 3

a[match("x",rownames(a)), match("z",colnames(a))]
#[1] NA

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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