R:如何找到apply产生错误的位置

Rod*_*igo 2 error-handling r apply

简单的问题是:如何找到我的data.frame中的哪个位置产生错误?

细节是:

我有一个数据框架,其中包含野外收集的动物的地理数据(纬度/经度),并存储在博物馆中.这些数据来自不同的来源(不同的博物馆和其他博物馆的列表).动物可能在一个或多个来源中列出,有时我们对同一动物有不同的坐标 - 由于倒圆或拼写错误.我想要的是从每一行获得所有坐标 - 而不是NA - 并计算最大值减去最小值,从而具有误差的大小.小错误可能会被忽略,否则我将不得不检查它们.

我正在使用以下代码:

#ALL is my data.frame with thousands of lines and about 100 columns
#ALL$LatDif will receive the differences in the coordinates for each row
#cLat <- c(18,21,46,54,63,77,85) # the columns with Latitudes from each museum
ALL$LatDif <- apply(ALL,1,function(x) if (any(!is.na(x[cLat]))) {max(x[cLat],na.rm=T)-min(x[cLat],na.rm=T)} else {NA})
Run Code Online (Sandbox Code Playgroud)

它应该工作正常.但在某些方面它说:

Error in max(x[cLat], na.rm = T) - min(x[cLat], na.rm = T) : 
  non-numeric argument to binary operator
Run Code Online (Sandbox Code Playgroud)

traceback()给了我:

2: FUN(newX[, i], ...) at #1
1: apply(TUDO, 1, function(x) if (any(!is.na(x[cLat]))) {
       max(x[cLat], na.rm = T) - min(x[cLat], na.rm = T)
   } else {
       NA
   })
Run Code Online (Sandbox Code Playgroud)

似乎在它的中间有某些角色,但我无法找到它.is.character()没有帮助我.使用a需要花费很长时间.有什么帮助吗?提前致谢!

Mat*_*rde 5

options(error=recover).这将在遇到错误时启动浏览器会话,并且在该会话中,您可以看到它正在阻塞的变量.当recover您要求选择框架时,请选择最深的框架.然后输入x以查看哪个功能有问题.

例如:

R> df <-data.frame(a=c('1', '2', '3', "stop('STOP')", '4'))
R> options(error=recover)
R> apply(df, 1, function(x) eval(parse(text=x)))
# Error in eval(expr, envir, enclos) : STOP
# 
# Enter a frame number, or 0 to exit   
# 
# 1: apply(df, 1, function(x) eval(parse(text = x)))
# 2: #1: FUN(newX[, i], ...)
# 3: #1: eval(parse(text = x))
# 4: eval(expr, envir, enclos)
# 
Selection: 4
# Called from: stop("STOP")
Browse[1]> x
#              a 
# "stop('STOP')" 
Run Code Online (Sandbox Code Playgroud)