Q:

where to put options (warn =2) in my function in r

I have a function with 100 lines of for loop. My function return warning message Warning message:
In f(init, x[[i]]) :
  longer object length is not a multiple of shorter object length.
However, I do not know from where this warning comes? So I tried to trace back this message. So, I search for this problem, I found I can turn this warning to error using this:
by setting
options(warn = 2)

or this 
options(error=utils::recover)

However, I do not really understand where I have to write these codes.
So, where should I write the options(warn = 2), inside my function? 
any help please?

A:

Do you want to know for which step inside the loop it fails? If so you could use safely from purrr. I tried writing something together, hope it helps. For my example though, everything fails, because I dont know what xvec and theta should be. Using safely, it will continue running even though hitting a error. You could also use print(i) inside the loop to see during which step it fails. 
library(purrr)

output_list <- vector("list", 100)

myfunc <- safely(function(x){

  fn <- function(theta) { sum ( 0.5*(xvec - theta[1])^2/theta[2] + 0.5* log(theta[2]) ) }
  optim(theta <- c(0,5), fn, hessian=TRUE,method = "L-BFGS-B",lower=c(0,0),control = list(trace=1))

  out

})

for(i in 1:100){

  output_list[[i]] <- myfunc(rnorm(1))

}

errors <- lapply(output_list, function(x) !is.null(x$error)) %>% unlist

