r - 有条件地显示通过 withCallingHandlers 捕获的警告消息

标签 r error-handling try-catch tidyverse

背景
我有一个简单的脚本,它遍历目录中可用的 CSV 文件,并使用 read_csv 将它们读入一个数据框。和 map_dfr分别发挥作用。该脚本可能会遇到缺少列的文件。在那种情况下 read_csv将产生一个警告,因为我通过 cols_only 指定列名,我想保留。
期望的结果
我希望能够在显示可选警告的情况下运行此脚本。我正在尝试使用 withCallingHandlers 捕获此输出然后,根据函数参数的值,显示警告或不执行任何操作并继续。
问题
即使 show_warnings 也不会显示警告是 TRUE .好像是 warning `withCallingHandlers 的元素不被评估。

例子

# Notes
# Conditionally import files and glide over files with missing columns

# Settings ----------------------------------------------------------------

# Libs
library("tidyverse")
library("fs")

# Constants
pth_tmp_files <- path_temp("temp_csvs")
dir_create(pth_tmp_files)

# Files -------------------------------------------------------------------

# Create a set of sample files
while (length(dir_ls(pth_tmp_files)) < 11) {
    write_csv(x = mtcars,
              file = file_temp("sample_csv_", pth_tmp_files, "csv"))
}

# Add one 'damaged' file
write_csv(
    x = subset(mtcars, select = -cyl),
    file = file_temp("broken_sample_csv_", pth_tmp_files, "csv")
)

# Importer ----------------------------------------------------------------

append_files <- function(files_list, show_warnings) {
    csv_reader <- function(import_file, show_warnings = show_warnings) {
        withCallingHandlers(
            suppressWarnings(expr = {
                read_csv(
                    file = import_file,
                    col_types = cols_only(cyl = col_integer(),
                                          am = col_integer())
                )
            }),
            warning = function(w) {
                if (show_warnings) {
                    warning(w, immediate. = TRUE)
                }
            }
        )

    }

    imported_files <- map_dfr(.x = files_list,
                              .f = ~ csv_reader(import_file = .x),
                              .id = "origin_file")

    mutate(imported_files, origin_file = path_ext_remove(path_file(origin_file))) %>%
        arrange(desc(origin_file))
}

# Tests -------------------------------------------------------------------

# Should return data.frame(tibble) object without warnings
append_files(dir_ls(pth_tmp_files), show_warnings = FALSE)
# Correct    

# Should show warnings and return identical object
append_files(dir_ls(pth_tmp_files), show_warnings = TRUE)
# Object returned with no warnings
笔记
  • 我最感兴趣的是正确使用 withCallingHandlers和/或 invokeRestart职能。我不想要使用 tryCatch 的解决方案因为我最感兴趣的是了解其他错误处理方法。
  • 最佳答案

    问题是您使用的是 suppressWarnings在您的expr = 内参数,因此您的 withCallingHandlers 无需处理任何警告包装器(实际上 suppressWarnings 已经在内部使用了 withCallingHandlers,所以它也增加了一层冗余。)
    关键是如果发出警告消息并且用户请求 show_warnings = FALSE,则使用重启条件“muffleWarning”调用重启。 .
    顺便说一句,您需要更改您的 show_warnings 的名称。内部函数中的参数或显式传递外部函数的show_warnings参数到您的map call - 否则 R 无法确定它正在处理的 promise 对象。

    append_files <- function(files_list, show_warnings) {
      
        csv_reader <- function(import_file, show_warnings = show_warnings) {
            
          withCallingHandlers(
                expr    = read_csv(file      = import_file,
                                   col_types = cols_only(cyl = col_integer(),
                                                         am  = col_integer())),
                warning = function(w) {
                           if(!show_warnings) tryInvokeRestart("muffleWarning")
                }
            )
        }
    
        imported_files <- map_dfr(.x = files_list,
                                  .f = ~ csv_reader(import_file = .x, show_warnings),
                                  .id = "origin_file")
    
        mutate(imported_files, 
               origin_file = path_ext_remove(path_file(origin_file))) %>%
        arrange(desc(origin_file))
    }
    
    所以现在我们有:
    append_files(dir_ls(pth_tmp_files), show_warnings = FALSE)
    #> # A tibble: 384 x 3
    #>    origin_file               am   cyl
    #>    <chr>                  <int> <int>
    #>  1 sample_csv_1950b846938     1     6
    #>  2 sample_csv_1950b846938     1     6
    #>  3 sample_csv_1950b846938     1     4
    #>  4 sample_csv_1950b846938     0     6
    #>  5 sample_csv_1950b846938     0     8
    #>  6 sample_csv_1950b846938     0     6
    #>  7 sample_csv_1950b846938     0     8
    #>  8 sample_csv_1950b846938     0     4
    #>  9 sample_csv_1950b846938     0     4
    #> 10 sample_csv_1950b846938     0     6
    #> # ... with 374 more rows
    

    append_files(dir_ls(pth_tmp_files), show_warnings = TRUE)
    #> # A tibble: 384 x 3
    #>    origin_file               am   cyl
    #>    <chr>                  <int> <int>
    #>  1 sample_csv_1950b846938     1     6
    #>  2 sample_csv_1950b846938     1     6
    #>  3 sample_csv_1950b846938     1     4
    #>  4 sample_csv_1950b846938     0     6
    #>  5 sample_csv_1950b846938     0     8
    #>  6 sample_csv_1950b846938     0     6
    #>  7 sample_csv_1950b846938     0     8
    #>  8 sample_csv_1950b846938     0     4
    #>  9 sample_csv_1950b846938     0     4
    #> 10 sample_csv_1950b846938     0     6
    #> # ... with 374 more rows
    #> Warning message:
    #> The following named parsers don't match the column names: cyl 
    

    关于r - 有条件地显示通过 withCallingHandlers 捕获的警告消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65013733/

    相关文章:

    r - 如何使 R data.table 在像 data.frame 这样的列分配中回收时抛出错误?

    Javascript:显式抛出错误对象与不抛出错误对象之间的区别

    php - Laravel 5 错误报告抑制

    web-services - ajax调用失败时在vb.net中获取xhr对象

    python - except 之后如何继续

    r - r 中不包括 NA 的列长度

    r - 根据以前的评级创建顺序排名

    r - 从矩阵中选择特定的行序列

    c++ - 正确尝试/捕获无序映射异常

    python try except yield 组合