可靠检查R中是否存在变量

时间:2018-02-05 16:48:54

标签: r error-handling exists defined

如何在R中检查是否存在或可靠地定义了某些内容?我有一个矩阵(称为confirmTabSwitch($event) { if (this.disableSwitching) { const confirm = window.confirm('Discard changes and switch tab?'); if (confirm) { this.disableSwitching = false; const liArr = Array.from(this.tabsetEl.nativeElement.querySelectorAll('ul li')); let tabIndex; liArr.forEach((li, i) => { if(li.contains($event.target)) { tabIndex = i; } }); setTimeout(() => this.tabset.tabs[tabIndex].active = true); } } } ),如下所示:

the_matrix

我如何首先检查是否定义了我希望从矩阵中检索的值,而不仅仅是返回错误?

2 个答案:

答案 0 :(得分:1)

我明白了。它是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)
}

答案 1 :(得分:0)

使用%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]
}