R tryCatch在for循环中跳过错误但不执行错误语句

时间:2017-09-19 08:50:13

标签: r error-handling try-catch

基本数据看起来像这样,有15列和更多行:

X:

    Zeit Boesel Dresden.Nord Dresden.Winckelmannstrasse 
   1 01.01.2011 01:00   2741    9961.169      NA   
   2 01.01.2011 02:00   3462    19144.478     NA   
   3 01.01.2011 03:00   3675    10772.111     NA       
   4 01.01.2011 04:00   4550    5255.695      NA       

Y:

    Zeit Boesel Dresden.Nord Dresden.Winckelmannstrasse 
   1 01.01.2011 01:00   274.24  272.76        273.27           
   2 01.01.2011 02:00   273.97  272.44        273.10   
   3 01.01.2011 03:00   274.11  272.42        273.09          
   4 01.01.2011 04:00   273.91  272.08        272.48         

我想在这些dfs上对各列进行cor.test,并在结果中仅保存p.values。 显然,第四列的for循环发生错误(仅包含NA)。

    result = numeric()

    for (i in 2:15)
    {tryCatch(
      {result = append(result, cor.test(x[,i], y[,i], na.action = "na.omit", method = "spearman")$p.value)}, 
        error=function(e) NA)}

通过使用tryCatch,跳过错误并继续循环,但错误语句NA不会附加到结果,因此它只包含13列。

为什么它不起作用,如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

这是因为tryCatch应该包裹cor.test()函数而不是append()函数。此外,您可以在此处使用sapply()代替for循环。

生成一些数据

x <- data.frame(A=sample(1:100, size = 20),
                B=sample(1:100, size = 20),
                C=sample(1:100, size = 20),
                D=sample(1:100, size = 20))
y <- data.frame(A=sample(1:100, size = 20),
                B=sample(1:100, size = 20),
                C=sample(1:100, size = 20),
                D=NA)

现在代码

result <- sapply(2:ncol(x), (function(i){
  tryCatch({cor.test(x[,i], y[,i], na.action = "na.omit", method = "spearman")$p.value},
         error = function(e) NA)
}))
result
[1] 0.7238886 0.2668126        NA

现在,result向量包含一个NA,对应于数字向量和一系列NA之间的相关性测试。