25  R: Capture Error & Warning

25.1 Example 1

Code
fn_Mean = function(x, ...){
  
  tryCatch(
    
      expr = {
        
          fn_n = function(x, na.rm = FALSE) ifelse(na.rm, length(na.omit(x)), length(x))
          n = fn_n(x, ...)
          AM = mean(x, ...)
          GM = exp(mean(log(x), ...))
          HM = 1 / mean(1/x, ...)
          Mean = list(n = n, AM = AM, GM = GM, HM = HM)
          return(Mean)
    
      },
      
      error = function(e){
          cat('\n An error has occurred! The error message is below. \n')
          print(e)
      },
      
      warning = function(w){
          cat('\n A warning has occurred!  The warning message is below. \n')
          print(w)
      },
      
      finally = {
          cat('\n Completed the fn_Mean run! \n')
      }
      
  )
  
}

25.2 Call 1: No error or warning

Code
A = c(NA, 12, 15, 14, 18)
fn_Mean(A, na.rm = TRUE)

 Completed the fn_Mean run! 
$n
[1] 4

$AM
[1] 14.75

$GM
[1] 14.5938

$HM
[1] 14.44126

25.3 Call 2: No error or warning

Code
B = c(NA, -12, 15, 14, 18)
fn_Mean(A, na.rm = TRUE)

 Completed the fn_Mean run! 
$n
[1] 4

$AM
[1] 14.75

$GM
[1] 14.5938

$HM
[1] 14.44126

25.4 Call 3: No error or warning

Code
C = c(NA, 12, Inf, 14, 18)
fn_Mean(A, na.rm = TRUE)

 Completed the fn_Mean run! 
$n
[1] 4

$AM
[1] 14.75

$GM
[1] 14.5938

$HM
[1] 14.44126

25.5 Call 4: No error or warning

Code
D = c(NA, 12, 0, 14, 18)
fn_Mean(D, na.rm = TRUE)

 Completed the fn_Mean run! 
$n
[1] 4

$AM
[1] 11

$GM
[1] 0

$HM
[1] 0

25.6 Call 5: No error or warning

Code
E = c(NA, 12, 0, NaN, 18)
fn_Mean(E, na.rm = TRUE)

 Completed the fn_Mean run! 
$n
[1] 3

$AM
[1] 10

$GM
[1] 0

$HM
[1] 0

25.7 Call 6: No error or warning

Code
G = c(NA, 12, 0, TRUE, F)
fn_Mean(G, na.rm = TRUE)

 Completed the fn_Mean run! 
$n
[1] 4

$AM
[1] 3.25

$GM
[1] 0

$HM
[1] 0

25.8 Call 7: Warning

Code
H = c(NA, 12, 0, "A", 18)
fn_Mean(H, na.rm = TRUE)

 A warning has occurred!  The warning message is below. 
<simpleWarning in mean.default(x, ...): argument is not numeric or logical: returning NA>

 Completed the fn_Mean run! 

25.9 Call 8: Error

Code
fn_Mean(J, na.rm = TRUE)

 An error has occurred! The error message is below. 
<simpleError in na.omit(x): object 'J' not found>

 Completed the fn_Mean run! 

25.10 Call 9: Error

Code
G = c(NA, 12, 0, TRUE, F)
fn_Mean(G, TRUE, na.rm = TRUE)

 An error has occurred! The error message is below. 
<simpleError in fn_n(x, ...): unused argument (TRUE)>

 Completed the fn_Mean run! 

25.11 Call 10: No error or warning

Code
G = c(NA, 12, 0, TRUE, F)
fn_Mean(G, na.rm = "TRUE")

 Completed the fn_Mean run! 
$n
[1] 4

$AM
[1] NA

$GM
[1] NA

$HM
[1] NA