[R tryCatch跳过错误的for循环,而不是执行错误的语句

问题描述:

基本数据看起来像这样有15列和多行:[R tryCatch跳过错误的for循环,而不是执行错误的语句

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循环发生错误(只包含NAs)。

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

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

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