可靠地检查 R 中是否存在变量
Reliable check if a variable exists in 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)
我如何首先检查我希望从矩阵中检索的值是否已定义,而不是仅仅返回错误?
像这样将 %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]
}
我明白了。它是 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)
}
我如何检查某些东西是否存在或在 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)
我如何首先检查我希望从矩阵中检索的值是否已定义,而不是仅仅返回错误?
像这样将 %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]
}
我明白了。它是 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)
}