bi_scholar bi_scholar - 5 months ago 29
R Question

R, Ways to access matrix elements if missing data is expected

I'm coming from a Java/C++ background and just recently started using R for real projects.

One thing I constantly struggle with is matrix (or any type of list/vector/etc.) accession.

Often times I have a set of data stored in a matrix-object and want to extract a row, perform some calculations, and then move on to the next row.
However, sometimes I can't just iterate through the matrix-rows but instead need to access them by row-name.

The problem arises, when there is no row of a given name (which tends to happen a lot in the data I'm dealing with). My function simply aborts.

What I'm desperately looking for is to access the matrix-row in a way, where I simply get a 'null'-, 'FALSE'-, whatever-Object, that enables me to continue running the script, even if data is missing.
Sure I can check whether my given rowname is part of all matrix-rownames, but that's simply not feasible runtime-wise.


wrap your statement into try() and then check if there was an error.

tmp <- matrix(1:4, 2, 2, dimnames = list(c("a","b"), c("c", "d")))
result <- try(tmp["x",])
if(inherits(result, "try-error")) result <- NA

see also the R help