Надежная проверка, существует ли переменная в R
Как я могу проверить, существует ли что-то или надежно определено в R? У меня есть матрица (называется the_matrix
) вот так:
#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)
Как я могу сначала проверить, определено ли значение, которое я хочу получить из матрицы, а не просто вернуть ошибку?
2 ответа
Решение
Я понял. Это обертка вокруг try, которая сама является оберткой для tryCatch. Вот функция:
#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)
}
Использовать %in%
оператор вместе с row.names
вот так:
rowname_to_check <- 'rowname_not_inmatrix'
if (rowname_to_check %in% row.names(the_matrix)) {
z_prime=the_matrix[rowname_to_check,3]
}