问题
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