0

Suppose I have a Null vector and Null List -

ot_vec = c()
msg_lst = list()

Further, suppose I have many user-defined functions. Now I want to use a tryCatch to append the outputs of the user-defined functions in the Null list and the messages from tryCatch in the Null vector one by one without printing the outputs and messages from tryCatch.

For e.g., if I define two user-defined functions for Square_Calculator and SquareRoot_Calculator using tryCatch, after running the following lines of code No outputs or error messages should be given directly here -

Codes

The outputs and error or warning messages should be appended in the Null List and Null Vector i.e., that list and vector should now take the following form - desired output

I was trying something like that -

MyTry

Though it is appending the output and error message to the ot_list and msg_vec within the function, it is not appending to the original Null List and Null Vector we have created a the very beginning.

Phil
  • 7,287
  • 3
  • 36
  • 66

1 Answers1

0

I believe the following will work. It may be possible to vectorize, but I will use a loop for the tryCatch. Also, it's set up to allow a list as input, as a list can have different data types within it. The example will be for square root, which returns an error on non-numeric and a warning on negative numbers. It will append to passed lists/vectors.

squareRoot <- function(x, ot, msg) {
  for (i in seq_along(x)) {
    xsq <- tryCatch(sqrt(x[[i]]),
                    error = function(cond) simpleError(trimws(cond$message)),
                    warning = function(cond) simpleWarning(trimws(cond$message))
    )
    
    if (inherits(xsq, "simpleError")) {
      ot <- c(ot, list(NA_real_))
      msg <- c(msg, "Error Detected")
    } else if (inherits(xsq, "simpleWarning")) {
      ot <- c(ot, list(NA_real_))
      msg <- c(msg, "Warning Detected")
    } else {
      ot <- c(ot, list(xsq))
      msg <- c(msg, "Run Successfully")
    }
  }
  
  list(ot = ot, msg = msg)
}

Now to test:

x <- list(5, "5", -5, "-5", "Test")
y <- list("A", 36, 81, NA_real_)

Out <- squareRoot(x, list(), c())

Out
$ot
$ot[[1]]
[1] 2.236068

$ot[[2]]
[1] NA

$ot[[3]]
[1] NA

$ot[[4]]
[1] NA

$ot[[5]]
[1] NA


$msg
[1] "Run Successfully" "Error Detected"   "Warning Detected" "Error Detected"  
[5] "Error Detected"

Out <- squareRoot(y, Out$ot, Out$msg)

Out
$ot
$ot[[1]]
[1] 2.236068

$ot[[2]]
[1] NA

$ot[[3]]
[1] NA

$ot[[4]]
[1] NA

$ot[[5]]
[1] NA

$ot[[6]]
[1] NA

$ot[[7]]
[1] 6

$ot[[8]]
[1] 9

$ot[[9]]
[1] NA


$msg
[1] "Run Successfully" "Error Detected"   "Warning Detected" "Error Detected"  
[5] "Error Detected"   "Error Detected"   "Run Successfully" "Run Successfully"
[9] "Run Successfully"

Avraham
  • 1,655
  • 19
  • 32