R中的陷印错误

时间:2015-10-14 15:28:43

标签: r try-catch

一个非常基本的问题。但我无法将此应用于我的代码。因此,在这里寻求帮助

我在运行此R代码时收到下面提到的错误

knn.pred <- knn(tdm.stack.nl_train, tdm.stack.nl_Test, tdm.cand_train, prob = TRUE)

>     Error in knn(tdm.stack.nl_train, tdm.stack.nl_Test, tdm.cand_train, prob = TRUE) : 
>       dims of 'test' and 'train' differ.

我想打印下面给出的错误消息。但是我无法做到这一点。我还不擅长编写函数..请帮助。

   out <- tryCatch( when error = {print('New words seen in testing data')})

2 个答案:

答案 0 :(得分:1)

使用try更好更容易:

knn.pred <- try(knn(tdm.stack.nl_train, tdm.stack.nl_Test, tdm.cand_train, prob = TRUE))

if (inherits(knn.pred, "try-error") { # error management
  print('New words seen in testing data')
}

答案 1 :(得分:0)

你可以这样做:

tryCatch(knn.pred <- knn(tdm.stack.nl_train, tdm.stack.nl_Test, tdm.cand_train, prob = TRUE),
         error = function(e) {
           stop('New words seen in testing data')
         })

这显示为:

 tryCatch(knn.pred <- knn(tdm.stack.nl_train, tdm.stack.nl_Test, tdm.cand_train, prob = TRUE),
          error = function(e) {
            stop('New words seen in testing data')
            })

 Error in value[[3L]](cond) : New words seen in testing data