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

And*_*ein 6 debugging r plyr dplyr

当我使用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))
Run Code Online (Sandbox Code Playgroud)

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

> 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, 
Run Code Online (Sandbox Code Playgroud)

无论如何,也许只是将id作为输入包含在每一次,以便于调试,这只是一种方法,但我想知道是否有一些更优雅的专业人士使用而不需要传递额外的变量.

安迪

小智 5

我用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
Run Code Online (Sandbox Code Playgroud)