Читать книгу The Big R-Book - Philippe J. S. De Brouwer - Страница 252

7.3.3 Attention Points When Using the Pipe

Оглавление

This construct will get into problems for functions that use lazy evaluation. Lazy evaluation is a feature of R that is introduced in R to make it faster in interactive mode. This means that those functions will only calculate their arguments when they are really needed. There is of course a good reason why those functions have lazy evaluation and the reader will not be surprised that they cannot be used in a pipe. So there are many functions that use lazy evaluation, but most notably are the error handlers. These are functions that try to do something, but when an error is thrown or a warning message is generated, they will hand it over to the relevant handler. Examples are try, tryCatch, etc. We do not really discuss error handling in any other parts of this book, so here is a quick primer.

try()

tryCatch()

handler

# f1 # Dummy function that from which only the error throwing part 0 # is shown. f1 <- function() { # Here goes the long code that might be doing something risky # (e.g. connecting to a database, uploading file, etc.) # and finally, if it goes wrong: stop(“Early exit from f1!”) # throw error } tryCatch(f1(), # the function to try error = function(e) {paste(“_ERROR_:”,e)}, warning = function(w) {paste(“_WARNING_:”,w)}, message = function(m) {paste(“_MESSSAGE_:”,m)}, finally=“Last command” # do at the end ) ## [1] “_ERROR_: Error in f1(): Early exit from f1!\n”

As can be understood from the example above, the error handler should not be evaluated if f1 does not throw an error. That is why they use error handling. So the following will not work:

# f1 # Dummy function that from which only the error throwing part # is shown. f1 <- function() { # Here goes the long code that might be doing something risky # (e.g. connecting to a database, uploading file, etc.) # and finally, if it goes wrong: stop(“Early exit from f1!”) # something went wrong } %>% tryCatch( error = function(e) {paste(“_ERROR_:”,e)}, warning = function(w) {paste(“_WARNING_:”,w)}, message = function(m) {paste(“_MESSSAGE_:”,m)}, finally=“Last command” # do at the end ) # Note that it fails in silence.

The Big R-Book

Подняться наверх