How to get the error message in try() with rmarkdown? - r

When I use rmarkdown::render to compile the following code into html,
```{r, error=T}
setClass('A', slots=c())
try(setClass('A', slots=c()))
```
I found that there is no error message shown in the html file for the second command, instead it is printed in the command line. Does anybody know to make the error message printed in the html file as well? Thanks.

here are 2 methods to print the error message
```{r, error=T}
setClass('A', slots=c())
#method 1
temp <- try(setClass('A', slots=c()))
message(temp)
#method 2
try(setClass('A', slots=c()))
message(geterrmessage())
```
found the 2 methods from Details section in ?try
try evaluates an expression and traps any errors that occur during the
evaluation. If an error occurs then the error message is printed to
the stderr connection unless options("show.error.messages") is false
or the call includes silent = TRUE. The error message is also stored
in a buffer where it can be retrieved by geterrmessage. (This should
not be needed as the value returned in case of an error contains the
error message.)

Related

R: Debugging and tracing messages?

Whereas options(warn=2) will prompt an error and hence enable debugging, I'm struggling with doing the same for messages.
For example, somewhere in my codebase, an unknown function seems to use jsonlite-package, which triggers the following message.
So my question is: Is there a convenient way to trace back the origins of messages?
Note: Using browser() doesn't seem to help, since messages are not shown in browser-mode.
You can use wrap your code in a call to withCallingHandlers to turn messages into errors:
withCallingHandlers(
message("example message"),
message = function(m) stop(m)
)
#Error in message("example message") : example message

Parse error in .Rmd

I'm trying to knit an .Rmd and I keep getting
Error in parse(text = x, srcfile = src) : <text>:1:1: unexpected '$'
The line that is generating this error message is:
$\frac{51}{60}$
Any idea why I'm getting this message? I've tried all variations of $ and / in the equation, and even copied and pasted a different fraction example I found online and still get that message
You're probably putting that line inside a chunk:
```{r}
# don't put me here!
```
Put it in the main body of the document instead.

R - Suppress try() output to console when trapping an Rselenium expression

The following code sends output to the console when the expression fails even though the try() argument silent = TRUE.
dd = try(unlist(remDr$findElement("css", "#ctl00_mainA")), silent = TRUE)
suppressMessages() does not suppress the output.
dd = suppressMessages(try(unlist(remDr$findElement("css", "#ctl00_mainA")), silent = TRUE))
try() is used to trap the error Selenium message: Unable to locate element: ......... The code logic works perfectly; the script continues to run as intended.
The message is not an Error that appears in red. The message is in black; the same color that results from print() and cat().
Echo is off. The source code does not print to the console.
I want to suppress the message while retaining the ability to send messages to the console with print() and cat().
Would appreciate any ideas.
Use remDr$findElements() instead with the same arguments. If the element you are looking for doesn't exist it just returns a zero length list which is easy to test for, and you don't get a lengthy error message printed to the console.

Knitting returns parse error

In attempting to knit a PDF. I'm calling a script that should return two ggplots by calling the chunk:
```{r, echo=FALSE}
read_chunk('Script.R')
```r
But receive the error
processing file: Preview-24a46368403c.Rmd
Quitting from lines 9-12 (Preview-24a46368403c.Rmd) Error in
parse(text = x, srcfile = src) : attempt to use zero-length
variable name Calls: <Anonymous> ... <Anonymous> -> parse_all ->
parse_all.character -> parse Execution halted
The script on its own runs and returns the two plots, but won't return them when knitted.
Similarly attempted to use source()
But got a similar error
Quitting from lines 7-10 (Preview-24a459ca4c1.Rmd) Error in
file(filename, "r", encoding = encoding) : cannot open the
connection Calls: <Anonymous> ... withCallingHandlers -> withVisible
-> eval -> eval -> source -> file Execution halted
While this does not appear to be a solution for you, this exact same error message appears if the chunk is not ended properly.
I experienced this error and traced it to ending chunk with `` instead of ```. Correcting the syntax of the chunk solved the problem I experienced with the same error message as you.
Are you sure that knitr is running from the directory you think it is? It appears that it is failing to find the file.
use an absolute path, if that fixes it, you've found your problem
once you've done that, you can use opts_knit$set(root.dir = "...") -- don't use setwd(.) if you want it (the cwd) to be maintained.
Knitr's default is the directory of the .Rmd file itself.
It may have to do with the "r" at the end of the triple backquotes demarcating your code chunk. There should be nothing after the triple backquotes, but I think the problem is specifically that the letter is "r".
The issue stems from the fact that R markdown processes backquoted statements starting with r as inline code, meaning it actually runs whatever is between the backquotes.
I had similar issues writing a problem set in an Rmd with this statement, which had backquoted text intended to be monospace but not run as inline code:
Use sapply or map to calculate the probability of a failure rate over r <- seq(.05, .5, .025).
When I knit the document, I got opaque error messages saying I had an improper assignment using <-. It was because instead of just displaying the backquoted statement in monospace, r <- seq(.05, .5, .025) was actually processed as R inline code of <- seq(.05, .5, .025)...thus the improper assignment error. I fixed my error by changing the variable name from r to rate.
The actual text of the error message in your question might refer to whatever follows your code chunk, as the knitting process is probably trying to run that as code. In this case, just removing that stray r at the end of the code chunk should fix the error.
You should use the following similar syntax, I had the same exact issue but got it fixed:
```{r views}
bank.df <- read.csv("C:/Users/User/Desktop/Banks.csv", header = TRUE) #load data
dim(bank.df) # to find dimension of data frame
head(bank.df) # show first six rows
```
the ``` has to be in the end of the line.
In my case was that I finished the code with four comas, not three . Check this and If you finished with four comas too, try to delete one of them.

How to return a error message in R?

I was wondering how one is able to produce error messages in R, especially from within a function?
Since you don't specify what you really want, all I just can say is take a look at
?message # prints a message but not stop execution
?warning # prints a warning message but not stop execution
?stop # stops execution of the current expression and executes an error action.
Simply include stop() inside your function/script
If you'd like an error message, include it inside stop() like so
stop("This is an error message")

Resources