2

I am running a for-loop to wrap a function across a large dataset. It's a fisheries function that performs an equation on a vector "ll". Vector ll is the crux of the for-loop, with a lot of wrangling being done to create ll for each iteration. I have included the important part of the loop here. mod<-removal(ll, method = "Burnham", Tmult = 5)

However, for the equation to work, the numbers in the vector need to be descending. If they are not, the function will run, but will fill the results (model stats) with NA's. For analysis purposes, the result if this happens should simply be 1.5*sum(ll). I would like to build a wrapper statement into this loop, that essentially says "if this warning should occur, then multiply sum(ll) by 1.5" but I can't figure out how to build that conditional in R. Any help is appreciated!

zephryl
  • 14,633
  • 3
  • 11
  • 30
GradStu
  • 51
  • 3

1 Answers1

2

You likely want to use tryCatch(). Using this example code, where the second element of vectors throws a warning:

vectors <- list(
  c(1, 2, 3),
  c(NA, NA, NA),
  c(7, 8, 9)
)

out <- numeric(length(vectors))
for (i in seq_along(vectors)) {
  out[[i]] <- max(vectors[[i]], na.rm = TRUE)
}
# Warning message:
# In max(vectors[[i]], na.rm = TRUE) :
#   no non-missing arguments to max; returning -Inf

out
# 3 -Inf    9

If you wanted to return -99 whenever a warning occurs, you would do:

for (i in seq_along(vectors)) {
  out[[i]] <- tryCatch(
    max(vectors[[i]], na.rm = TRUE),
    warning = \(w) -99
  )
}

out
# 3 -99    9

However, it's safer to just handle a specific warning:

for (i in seq_along(vectors)) {
  out[[i]] <- tryCatch(
    max(vectors[[i]], na.rm = TRUE),
    warning = \(w) {
      if (grepl("no non-missing arguments to max; returning -Inf", w$message)) {
        -99
      } else {
        max(vectors[[i]], na.rm = TRUE)
      }
    }
  )
}

out
# 3 -99    9
zephryl
  • 14,633
  • 3
  • 11
  • 30
  • Thank you so much, that worked perfectly. I however, have encountered another issue, maybe you can help out on. There is another, separate warning that occurs. Which, if this warning is invoked, there needs to be a different operation to occur with the vector. I have tried nesting another trycatch() within the else statement, but to no avail. Any idea on how to handle this? – GradStu Feb 22 '23 at 17:25
  • Could you post as a new question with more details? i.e., code / data sufficient to reproduce the issue and the code you tried (i.e., a [reprex](https://stackoverflow.com/a/5963610/17303805)). – zephryl Feb 22 '23 at 17:38
  • done, thank you https://stackoverflow.com/questions/75537538/handling-several-warnings-differently-in-for-loop-trycatch – GradStu Feb 22 '23 at 19:52