Show which line caused the error

There was a similar question Can R Studio show me which line number in my code was called last when an error occurs?, but the question has been closed and the solution doesn't work for me.

The solution was:

When you get an error, usually you have a modal with two options in console: "Traceback" and "Rerun with debug". If you choose "Rerun with debug", it'll show you the line where error was thrown.

I don't see "Rerun with debug". Here is a sample code that replicates this issue:

# script
test <- function(a, b) {
    a+b
}
test(1, "b")

All I can see is:

source("~/.active-rstudio-document")
Error in a + b : non-numeric argument to binary operator

That's because the error is detected by the interpreter before the code actually executes. You need an example that is syntactically correct but blows up for some reason when executed.

Then maybe this should be a feature request? For whatever reason that breaks the code, I want to know where it is. This is very important especially when I have many nested functions.

Something that might help is traceback():

test <- function(a, b) {
  a+b
}

f <- function(x){
  test(x, "b")
}

f(1)
#> Error in a + b : non-numeric argument to binary operator

traceback()
#> 2: test(x, "b") at #2
#> 1: f(1)

When you have nested functions it shows you where the last error occurred, tracing through multiple levels of depth.

2 Likes

@prubin, I'm not seeing where there is a syntactic error. Am I missing something?

1 Like

@startz I guess that depends on your definition of syntax. Is there a better descriptor for violating a type restriction in a function argument?

Not sure of the right word. It's not a syntax violation because R doesn't impose type restrictions on function arguments. It's a runtime error. Here's an (admittedly silly) example.

+  <- function(a,b) paste(a,b)
test <- function(a,b) a+b
test(1,"b")
[1] "1 b"

Also, while RStudio doesn't seem to show the "rerun with debug" for this type of error created by "+", this seems to work:

options(error = recover)
source("~/.active-rstudio-document")
2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.