How to set the width of an error message in R?

Viewed 119

I know you can set the width of your R output

> options(width = 20)
> 1:30
 [1]  1  2  3  4  5
 [6]  6  7  8  9 10
[11] 11 12 13 14 15
[16] 16 17 18 19 20
[21] 21 22 23 24 25
[26] 26 27 28 29 30

How do you set the error message to be width 20?

> options(width = 20)
> IWantMyErrorMessageToBeWidth20
Error: object 'IWantMyErrorMessageToBeWidth20' not found
2 Answers

This question is very interesting for me, and I would like to try to answer it. Please correct me if I'm wrong in some parts.

When you run 1:30, R will execute print(1:30)(Or more specifically, print.default(1:30)) behind the screen. Debugging inside this function, you will find that if you don't provide one argument width, it will directly use the width set in options(). To change the output from print(), you can either change the width in options() or write the code like print(1:30, width=10). Therefore, you can control the width in the code.

However, IWantMyErrorMessageToBeWidth20 are handled in another way. I assume R will first check if IWantMyErrorMessageToBeWidth20 exists in the memory, and find there's no object called IWantMyErrorMessageToBeWidth20, and then trigger the internal stop function in the R interpreter. I guess there's no width argument in the internal stop function.

Therefore, I would suggest you to follow Allan's advice.

As said in the comments, you can catch the error and process it like this

tryCatch(
  IWantMyErrorMessageToBeWidth20,
  error = function(err) {
    msg <- conditionMessage(err)
    stop(substr(as.character(msg), 1, 20), call. = FALSE)
  }
)

# Error: object 'IWantMyError
Related