cptn
cptn

Reputation: 703

Find out WHERE an error occurs in R when debugging

How can i find out WHERE the error occurs?

i've got a double loop like this

companies <- # vector with all companies in my data.frame
dates <- # vector with all event dates in my data.frame

for(i in 1:length(companies)) { 
  events_k <- # some code that gives me events of one company at a time

  for{j in 1:nrow(events_k)) {
  # some code that gives me one event date at a time
  results <- # some code that calculates stuff for that event date

}

mylist[[i]] <- results # store the results in a list
}

In this code I got an error (it was something like error in max(i)...) The inner loop works perfectly. So by leaving out the outer loop and manually enter the company ID's until that error appeared, I found out for which company there was something wrong. My data.frame had letters in a vector with daily returns for that specific company.

For a next time: Is there a way in R to find out WHERE (or here FOR WHICH COMPANY) the error appears? It could save a lot of time!

Upvotes: 5

Views: 2955

Answers (2)

flodel
flodel

Reputation: 89057

What I like to use is:

options(error = recover)

You only need to run it once at the beginning of your session (or add it to your .Rprofile file)

After that, each time an error is thrown you will be shown the stack of function calls that led to the error. You can select any of these calls and it will be as if you had run that command in browser() mode: you will be able to look at the variables in the calling environment and walk through the code.

More info and examples at ?recover.

Upvotes: 5

coffeinjunky
coffeinjunky

Reputation: 11514

It is difficult to know without explicit code that we can run, but my guess is that changing your code to

 for(i in companies) { 
    for(j in dates) {

or alternatively

 for(i in 1:length(companies)) { 
    for(j in 1:length(dates)) {

may solve the issue. Note the ( in the second loop. If not, it might be a good idea to edit your example to have some code / data that produces the same error.

To figure out where it occurs, you can always add print(i) or something like that at a suitable place in the code.

Upvotes: 0

Related Questions