gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:23:57 24 4
gpt4 key购买 nike

如何检查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)

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

最佳答案

我想到了。它是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 - 可靠检查R中是否存在变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48627476/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com