Customize error message when compiling PDF

孤人 提交于 2019-12-24 11:27:44

问题


Given the following R knitr document:

\documentclass{article}
\begin{document}

<<data>>=
opts_chunk$set(comment = NA)  # omits "##" at beginning of error message
x <- data.frame(x1 = 1:10)
y <- data.frame()
@ 

<<output_x>>=
if (nrow(x) == 0) stop("x is an empty data frame.") else summary(x)
@

<<output_y>>=
if (nrow(y) == 0) stop("y is an empty data frame.") else summary(y)
@

\end{document}

As expected, the last chunk returns an error with the custom message. The compiled PDF looks a little different:

Error: y is an empty data frame.

I want this text to just be

y is an empty data frame.

Without the Error: part or the red color. Can I achieve this? How?

Edit: I was able to make it in the mock data through the following workaround:

<<output_y>>=
if (nrow(y) == 0) cat("y is an empty data frame.") else summary(y)
@

However, that doesn't work with my real data, because I need the function to be stopped at that point.


回答1:


Although I do not understand why an error should not be called Error, you are free to customize the output hook error to remove Error: from the message:

library(knitr)
knit_hooks$set(error = function(x, options) {
  knitr:::escape_latex(sub('^Error: ', '', x))
})



回答2:


You could do something like this. options("show.error.messages" = FALSE) turns off error messages, so you could temporarily employ that once the if statement is entered and use on.exit to reset it.

This way, stop stops the function, Error: is avoided, and the desired message is printed in red.

> f <- function(x) {
      if(x > 5) {
          g <- getOption("show.error.messages")
          options(show.error.messages = FALSE)
          on.exit(options(show.error.messages = g))
          message("x is greater than 5.")
          stop()
      }
      x
  }
> f(2)
# [1] 2
> f(7)
# x is greater than 5.

Note: I'm not exactly sure how safe this is and I'm not a big supporter of changing options settings inside functions.



来源:https://stackoverflow.com/questions/25493026/customize-error-message-when-compiling-pdf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!