Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在循环中使用geterrmessage()-R_R_Error Handling - Fatal编程技术网

在循环中使用geterrmessage()-R

在循环中使用geterrmessage()-R,r,error-handling,R,Error Handling,我的目标是捕获R抛出的错误并将其存储在对象中 以下是一些虚拟代码: for(i in 1:length(a)){try( if (i==4)(print(a[i]/"b"))else(print(a[i]/b[i])) )} [1] -0.125 [1] -0.2857143 [1] -0.5 Error in a[i]/"b" : non-numeric argument to binary operator [1] -1.25 [1] -2 [1] -3.5 [1] -8 [1] Inf

我的目标是捕获R抛出的错误并将其存储在对象中

以下是一些虚拟代码:

for(i in 1:length(a)){try(
if (i==4)(print(a[i]/"b"))else(print(a[i]/b[i]))
)}

[1] -0.125
[1] -0.2857143
[1] -0.5
Error in a[i]/"b" : non-numeric argument to binary operator
[1] -1.25
[1] -2
[1] -3.5
[1] -8
[1] Inf
[1] 10
所以我想在第四次迭代中捕捉到错误是:
a[I]/“b”中的错误:二进制运算符的非数值参数
进入一个对象,比如:

error<-()
iferror(error[i]<-geterrmessage())
这样以后我就可以检查
错误
对象,了解错误发生的位置和原因


如果您能帮助我编写一段代码,这段代码将非常优秀,受到高度赞赏

我希望以下函数能有所帮助:

a <- c(0:6)
b <- c(-3:3)

create_log <- function(logfile_name, save_path) {
  warning("Error messages not visible. Use closeAllConnections() in the end of the script")
  if (file.exists(paste0(save_path, logfile_name))) {
    file.remove(paste0(save_path, logfile_name))
  }
  fid <- file(paste0(save_path, logfile_name), open = "wt")
  sink(fid, type = "message", split = F) # warnings are NOT displayed. split=T not possible.
  sink(fid, append = T, type = "output", split = T) # print, cat
  return(NULL)
}


create_log("test.csv", "C:/Test/")
for(i in 1:length(a)){try(
  if (i==4)(print(a[i]/"b"))else(print(a[i]/b[i]))
)}
closeAllConnections()

a您看过
?tryCatch
?可能有用
a <- c(0:6)
b <- c(-3:3)

create_log <- function(logfile_name, save_path) {
  warning("Error messages not visible. Use closeAllConnections() in the end of the script")
  if (file.exists(paste0(save_path, logfile_name))) {
    file.remove(paste0(save_path, logfile_name))
  }
  fid <- file(paste0(save_path, logfile_name), open = "wt")
  sink(fid, type = "message", split = F) # warnings are NOT displayed. split=T not possible.
  sink(fid, append = T, type = "output", split = T) # print, cat
  return(NULL)
}


create_log("test.csv", "C:/Test/")
for(i in 1:length(a)){try(
  if (i==4)(print(a[i]/"b"))else(print(a[i]/b[i]))
)}
closeAllConnections()