Search code examples
rerror-handlingexistsdefined

Reliable check if a variable exists in R


How can I check if something exists or is defined reliably in R? I have a matrix (called the_matrix) like so:

#Structure of the matrix
    row.names   V1  V2  V3
1   22936   22936   3134    1222
2   285855  285855  5123    1184
3   10409   10409   2857    1142
4   6556    6556    1802    1089

#Get values from the matrix
z=the_matrix['22936',3]
#z equals 1222
z_prime=the_matrix['rowname_not_inmatrix',3]
#returns an error:
#Error in the_matrix["rowname_not_inmatrix", 3] : subscript out of bounds
#(z_prime remains not defined)

How can I first check as to whether the value I wish to retrieve from the matrix is defined, rather than just returning an error?


Solution

  • I figured it out. It is a wrapper around try, which is itself a wrapper for tryCatch. Here is the function:

    #this tries to evaluate the expression and returns it, but if it does not work, returns the alternative value. It is simply a wrapper for trycatch. 
    #This is similar to python's try except
    #e.g.
    #the_value=tryExcept(the_matrix[[1]][i,3],0)
    #This will return the value of  the_matrix [[1]][i,3], unless it does not exist, in which case it will return zero
    
    tryExcept <- function(expr,alternative)
    {
        tryCatch(expr,error=function(e) alternative)
    }