在ddply中找到数据源错误的原因

时间:2013-07-12 21:45:30

标签: r error-handling plyr

我喜欢使用plyr,但有时基础数据会抛出我无法找到的错误。

例如,我创建了一个求和函数,如果x == 8会抛出错误:

df <- data.frame(x = rep(1:10,3), y = runif(30))

ddply(df,
      .(x),
      function (z) { 
        if(z$x[1] == 8) {
          stop("There's an error somewhere.")
        }
        return(sum(z$y))
        })

假装我不知道导致错误的是什么,有没有办法报告哪些数据行导致错误?

2 个答案:

答案 0 :(得分:4)

以下是使用tryCatch

的示例
set.seed(1)
df <- data.frame(x = rep(1:10,3), y = runif(30))

f = function (z) { 
        if(z$x[1] == 8) {
          stop("There's an error somewhere.")
        }
        return(sum(z$y))
    }

ddply(df, .(x), function(z) {
         tryCatch(f(z), error = function(e) {
              print("offending block is"); print(z)
         })
     })

#[1] "offending block is"
#  x         y
#1 8 0.6607978
#2 8 0.9919061
#3 8 0.3823880
#Error in list_to_dataframe(res, attr(.data, "split_labels")) : 
#  Results must be all atomic, or all data frames

答案 1 :(得分:0)

当您使用ddply时,您可以在函数内部使用data.frame df的整个子集作为变量z。所以,你可以在那里做任何你想做的事。

z[z$x==8,]

例如,会给你有问题的行。如果您想知道哪个子集引发错误,您可以执行以下操作:

if (z$x[1] ==8) {
  stop(paste('There is an error in the', unique(z$x), 'subset of df'))
}

否则,你必须更清楚地解释你在寻找什么。包括错误的一组工作示例数据以及关于您想知道什么的信息的示例将会有很长的路要走...现在看来,我只是在猜测!