【问题标题】:R tryCatch skips error in for loop but error statement is not executedR tryCatch 在 for 循环中跳过错误但未执行错误语句
【发布时间】:2017-09-19 08:50:13
【问题描述】:

基本数据如下所示,有 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       

是的:

    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 列。

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

【问题讨论】:

    标签: r error-handling try-catch


    【解决方案1】:

    这是因为 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 之间的相关性检验。

    【讨论】:

      猜你喜欢
      • 2015-08-20
      • 2017-02-06
      • 2021-06-16
      • 2013-01-22
      • 2022-01-15
      • 1970-01-01
      • 1970-01-01
      • 2019-01-07
      • 1970-01-01
      相关资源
      最近更新 更多