【问题标题】:How do you include data frame output inside warnings and errors?如何在警告和错误中包含数据框输出?
【发布时间】:2014-11-22 21:14:55
【问题描述】:

如何在消息、警告或错误中包含数组或数据框输出?

默认情况下,输出被deparseing 每列折叠,这没有用。这是一个使用cars 数据集的示例。

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)

【问题讨论】:

    标签: r error-handling


    【解决方案1】:

    打印输出,使用capture.output() 重新捕获它,然后折叠成由换行符分隔的单个字符串。

    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() 现在在assertive.base 中可用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-24
      • 2018-10-31
      • 2011-09-20
      • 2015-10-05
      • 2019-04-27
      • 1970-01-01
      • 2011-02-27
      相关资源
      最近更新 更多