【问题标题】:Debugging in plyr or dplyr - seeing which group在 plyr 或 dplyr 中调试 - 查看哪个组
【发布时间】:2016-04-18 18:40:16
【问题描述】:

当我使用 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 作为输入包括在内,但我想知道是否有更优雅的东西可供专业人员使用而无需传递额外的变量。

安迪

【问题讨论】:

    标签: r debugging dplyr plyr


    【解决方案1】:

    我一直在使用 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
    

    【讨论】:

      猜你喜欢
      • 2015-01-08
      • 1970-01-01
      • 1970-01-01
      • 2020-05-21
      • 2020-11-30
      • 1970-01-01
      • 2014-02-16
      • 1970-01-01
      • 2019-02-25
      相关资源
      最近更新 更多