Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you include data frame output inside warnings and errors?

How can I include array or data frame output in a message, warning or error?

By default, the output is collapsed by deparseing each column, which isn't useful. Here's an example, using the cars dataset.

message(cars)
## c(4, 4, 7, 7, 8, 9, 10, 10, 10, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 16, 16, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 20, 20, 20, 20, 20, 22, 23, 24, 24, 24, 24, 25)c(2, 10, 4, 22, 16, 10, 18, 26, 34, 17, 28, 14, 20, 24, 28, 26, 34, 34, 46, 26, 36, 60, 80, 20, 26, 54, 32, 40, 32, 40, 50, 42, 56, 76, 84, 36, 46, 68, 32, 48, 52, 56, 64, 66, 54, 70, 92, 93, 120, 85)
like image 870
Richie Cotton Avatar asked Sep 28 '14 09:09

Richie Cotton


1 Answers

Print the output, recapture it using capture.output(), and collapse into a single string separated by newlines.

print_and_capture <- function(x)
{
  paste(capture.output(print(x)), collapse = "\n")
}

message(print_and_capture(cars))
##    speed dist
## 1      4    2
## 2      4   10
## # etc.

stop("An error was found in the cars dataset:\n", print_and_capture(cars))
## Error: An error was found in the cars dataset:
##    speed dist
## 1      4    2
## 2      4   10
## # etc.

print_and_capture() is now available in assertive.base.

like image 152
2 revs Avatar answered Oct 24 '22 09:10

2 revs