catch R tryCatch()超出范围的异常,以忽略执行

问题描述 投票:0回答:1

问题:

R tryCatch()需要处理已知错误。

我正在使用词向量矩阵来运行向量词位置。我正在寻求添加R tryCatch()来处理或赶超此下标。单词搜索的预期行为。在R中捕获,忽略异常的确切方法是什么?我应该使用什么异常代码来越界?

例如:

word1 = 'This'
word2 = 'Happy'

此组合在单词向量内的上下文搜索中不会匹配。因此,下标超出范围表示此匹配项不存在。

代码:

'''
    word_vectors[word1, , drop=FALSE] + word_vectors[word2, , drop=FALSE]
'''

错误信息:

'''
run_glove_search(word1, word2, word_vectors)
Error in word_vectors[word1, , drop = FALSE] : subscript out of bounds
> View(word_vectors)
'''

错误是由于下标超出范围,这是由于不匹配的单词组合所致。因此,这是预期的行为。

数据示例:注意:词矩阵是一个大矩阵75800,所以我只显示1行统计示例

'''
This    0.175438308 0.1229126933    -0.792327086    -0.698233553    0.407953490 0.362040523 0.258780885 0.352198675 -0.170637061    -0.512016098    0.408881291 -0.0866425339   0.0510299517    -0.150036589    0.002336813 0.390699917 -0.635815296    -0.295312958
'''
exception try-catch-finally
1个回答
0
投票

代码解决方案:TryCatch()与error = function(e)无关,因为我知道并期望会发生此错误,所以我可以将NULL赋给function(e)的e,因为我不需要任何错误消息。

  tryCatch({
    gws <- word_vectors[word1, , drop=FALSE] + word_vectors[word2, , drop=FALSE]
    cos_sim = sim2(x = word_vectors, y = gws, method = "cosine", norm = "l2")
    head(sort(cos_sim[,1], decreasing = TRUE), 7)
    },
    error = function(e){e=NULL}
  ) 
© www.soinside.com 2019 - 2024. All rights reserved.