在 plyr 或 dplyr 中调试 - 查看哪个组

Debugging in plyr or dplyr - seeing which group

当我使用 plyr 和 dplyr 分析按 id 分组的大数据集时,我的函数有时会出错。我可以使用 browser() 或 debugger() 来探索发生了什么,但一个问题是我不知道问题出在第一个 id 还是第 100 个。我可以使用调试器让我在错误处停止,但是除了仅将 id 作为调试目的的函数输入包括在内之外,是否有一种简单的方法来查看是什么 id 导致了问题?我用下面的例子来说明。

meanerr = function(y) {
  m = mean(y)
  stopifnot(!is.na(m))
  return(m)
}

d = data.frame(id=c(1,1,1,1,2,2),y=c(1,2,3,4,5,NA))
dsumm = ddply(d,"id",summarise,mean=meanerr(y))

当然这会导致下面的错误,当我进入转储时,我只需要知道在哪里看(见下文)

> options(error=dump.frames)
> source('~/svn/pgm/test_debug_ddply.R')
Error: !is.na(m) is not TRUE
> debugger()
Message:  Error: !is.na(m) is not TRUE
Available environments had calls:
1: source("~/svn/pgm/test_debug_ddply.R")
2: withVisible(eval(ei, envir))
3: eval(ei, envir)
4: eval(expr, envir, enclos)
5: test_debug_ddply.R#9: ddply(d, "id", summarise, mean = meanerr(y))
6: ldply(.data = pieces, .fun = .fun, ..., .progress = .progress, .inform = .inform, .parallel = .
7: llply(.data = .data, .fun = .fun, ..., .progress = .progress, .inform = .inform, .parallel = .p
8: loop_apply(n, do.ply)
9: (function (i) 
{
    piece <- pieces[[i]]
    if (.inform) {
        res <- try(.fun(piece, ...))

10: .fun(piece, ...)
11: eval(cols[[col]], .data, parent.frame())
12: eval(expr, envir, enclos)
13: meanerr(y)
14: test_debug_ddply.R#3: stopifnot(!is.na(m))
15: stop(sprintf(ngettext(length(r), "%s is not TRUE", "%s are not all TRUE"), ch), call. = FALSE, 

无论如何,也许每次都将 id 作为输入以方便调试是可行的方法,但我想知道是否有专业人士使用的更优雅的东西而不需要传递额外的变量。

安迪

我一直 运行 使用 dplyr 的 group_by() 我在使用我常用的 options(error=recover).

时遇到了麻烦

我发现将有问题的函数包装在 tryCatch() 中可以达到目的:

> dsumm = ddply(d,"id",summarise,mean=tryCatch(meanerr(y),error=function(e){"error"}))
> dsumm
  id   mean
1  1    2.5
2  2  error