attempt包测试2_Try_Catch_20200203M
1.设置当前工作目录
getwd()
2.导入R包
library(attempt)
3.测试
#@ attempt() is a wrapper around base try() that allows you to insert a custom messsage on error.
attempt(log(“a”))
Error: 数学函数中用了非数值参数
attempt(log(“a”), msg = “Nop!”)
Error: Nop!
#@ You can make it verbose (i.e. returning the expression):
attempt(log(“a”), msg = “Nop!”, verbose = TRUE)
Error in log(“a”): Nop!
#@ Of course the result is returned if there is one:
attempt(log(1), msg = “Nop!”, verbose = TRUE)
[1] 0
#@ As with try(), the result can be saved as an error object:
a <- attempt(log(“a”), msg = “Nop!”, verbose = TRUE)
Error in log(“a”): Nop!
#@ You can check if the result is an error with is_try_error()
a <- attempt(log(“a”), msg = “Nop!”, verbose = FALSE)
Error: Nop!
is_try_error(a)
[1] TRUE
#@ silent_attempt
silent_attempt() is a wrapper around silently() (see further down for more info) and attempt(). It attempts to run the expr, stays silent if the expression succeeds, and returns error or warnings if any.
silent_attempt(log(“a”))
Error: 数学函数中用了非数值参数
silent_attempt(log(1)) # 如果没有问题,则没有输出
#@ try catch
You can write a try catch with these params:
expr the expression to be evaluated
e a mapper or a function evaluated when an error occurs
w a mapper or a function evaluated when a warning occurs
f a mapper or an expression which is always evaluated before returning or exiting
In .e and .f, the .x refers to the error / warning object.
#@ with mappers
try_catch(expr = log(“a”),
.e = ~paste0(“There is an error:”, .x),
.w = ~paste0(“This is a warning:”, .x))
[1] “There is an error:Error in log(“a”): 数学函数中用了非数值参数\n”
try_catch(log(“a”),
.e = ~ stop(.x),
.w = ~ warning(.x))
Error in log(“a”) : 数学函数中用了非数值参数
try_catch(matrix(1:3, nrow = 2),
.e = ~ print(.x),
.w = ~ print(.x))
try_catch(expr = 2 + 2,
.f = ~ print(“Using R for addition… ok I’m out!”))
[1] “Using R for addition… ok I’m out!”
[1] 4
#@ As usual, the handlers are set only if you call them:
try_catch(matrix(1:3, nrow = 2), .e = ~print(“Error”))
[,1] [,2]
[1,] 1 3
[2,] 2 1
Warning message:
In matrix(1:3, nrow = 2) : 数据长度[3]不是矩阵行数[2]的整倍
try_catch(matrix(1:3, nrow = 2), .w = ~ print(“Warning”))
[1] “Warning”
#@ Traditionnal way
{attempt} is flexible in how you can specify your arguments.
You can, as you do with {base} tryCatch(), use a plain old function:
try_catch(log(“a”),
.e = function(e){
print(paste0(“There is an error: “, e))
print(“OK, let’s save this”)
time <- Sys.time()
a <- paste(”+ At”,time, “, \nError:”,e)
print(paste(“log saved on log.txt at”, time))
print(“let’s move on now”)
})
[1] “There is an error: Error in log(“a”): 数学函数中用了非数值参数\n”
[1] “OK, let’s save this”
[1] “log saved on log.txt at 2020-02-03 21:37:56”
[1] “let’s move on now”
#@ You can even mix both:
try_catch(log(“a”),
.e = function(e){
paste("There is an error: ", e)
},
.f = ~ print(“I’m not sure you can do that pal!”))
[1] “I’m not sure you can do that pal!”
[1] “There is an error: Error in log(“a”): 数学函数中用了非数值参数\n”
try_catch(log(“a”),
.e = ~ paste0("There is an error: ", .x),
.f = function() print(“I’m not sure you can do that pal!”))
[1] “I’m not sure you can do that pal!”
[1] “There is an error: Error in log(“a”): 数学函数中用了非数值参数\n”
#@ try_catch_df()
try_catch_df() returns a tibble with the call, the error message if any, the warning message if any, and the value of the evaluated expression or “error”. The values will always be contained in a list-column.
res_log <- try_catch_df(log(“a”))
res_log
A tibble: 1 x 4
call error warning value
1 “log(“a”)” 数学函数中用了非数值参数 NA
res_log$value
[[1]]
[1] “error”
res_matrix <- try_catch_df(matrix(1:3, nrow = 2))
res_matrix
A tibble: 1 x 4
call error warning value
1 matrix(1:3, nrow~ NA 数据长度[3]不是矩阵行数[2]的整倍~
res_matrix$value
[[1]]
[,1] [,2]
[1,] 1 3
[2,] 2 1
res_success <- try_catch_df(log(1))
res_success
A tibble: 1 x 4
call error warning value
1 log(1) NA NA
res_success$value
[[1]]
[1] 0
#@ map_try_catch()
map_try_catch() and map_try_catch_df() allow you to map on a list of arguments l, to be evaluated by the function in fun.
map_try_catch(l = list(1,3,“a”), fun = log, .e = ~ .x)
[[1]]
[1] 0
[[2]]
[1] 1.098612
[[3]]
Warning message:
lang()
is deprecated as of rlang 0.2.0.
Please use call2()
instead.
This warning is displayed once per session.
map_try_catch_df(list(1,3,“a”),log)
A tibble: 3 x 4
call error warning value
1 “.Primitive(“log”)(1)” NA NA
2 “.Primitive(“log”)(3)” NA NA
3 “.Primitive(“log”)(”~ 数学函数中用了非数值参数~ NA
4.结束
sessionInfo()
R version 3.6.2 (2019-12-12)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 18363)
Matrix products: default
locale:
[1] LC_COLLATE=Chinese (Simplified)_China.936
[2] LC_CTYPE=Chinese (Simplified)_China.936
[3] LC_MONETARY=Chinese (Simplified)_China.936
[4] LC_NUMERIC=C
[5] LC_TIME=Chinese (Simplified)_China.936
attached base packages:
[1] stats4 parallel stats graphics grDevices utils
[7] datasets methods base
other attached packages:
[1] attempt_0.3.0 Biostrings_2.54.0 XVector_0.26.0
[4] IRanges_2.20.2 S4Vectors_0.24.2 BiocGenerics_0.32.0
loaded via a namespace (and not attached):
[1] Seurat_3.1.2 TH.data_1.0-10
[3] Rtsne_0.15 colorspace_1.4-1
[5] seqinr_3.6-1 pryr_0.1.4
[7] ggridges_0.5.2 rstudioapi_0.10
[9] leiden_0.3.2 listenv_0.8.0
[11] npsurv_0.4-0 ggrepel_0.8.1
[13] fansi_0.4.1 alakazam_0.3.0
[15] mvtnorm_1.0-12 codetools_0.2-16
[17] splines_3.6.2 R.methodsS3_1.7.1
[19] mnormt_1.5-5 lsei_1.2-0
[21] TFisher_0.2.0 zeallot_0.1.0
[23] ade4_1.7-13 jsonlite_1.6
[25] packrat_0.5.0 ica_1.0-2
[27] cluster_2.1.0 png_0.1-7
[29] R.oo_1.23.0 uwot_0.1.5
[31] sctransform_0.2.1 readr_1.3.1
[33] compiler_3.6.2 httr_1.4.1
[35] backports_1.1.5 assertthat_0.2.1
[37] Matrix_1.2-18 lazyeval_0.2.2
[39] cli_2.0.1 htmltools_0.4.0
[41] prettyunits_1.1.0 tools_3.6.2
[43] rsvd_1.0.2 igraph_1.2.4.2
[45] gtable_0.3.0 glue_1.3.1
[47] RANN_2.6.1 reshape2_1.4.3
[49] dplyr_0.8.3 Rcpp_1.0.3
[51] Biobase_2.46.0 vctrs_0.2.1
[53] multtest_2.42.0 gdata_2.18.0
[55] ape_5.3 nlme_3.1-142
[57] gbRd_0.4-11 lmtest_0.9-37
[59] stringr_1.4.0 globals_0.12.5
[61] lifecycle_0.1.0 irlba_2.3.3
[63] gtools_3.8.1 future_1.16.0
[65] zlibbioc_1.32.0 MASS_7.3-51.4
[67] zoo_1.8-7 scales_1.1.0
[69] hms_0.5.3 sandwich_2.5-1
[71] RColorBrewer_1.1-2 reticulate_1.14
[73] pbapply_1.4-2 gridExtra_2.3
[75] ggplot2_3.2.1 stringi_1.4.3
[77] mutoss_0.1-12 plotrix_3.7-7
[79] caTools_1.17.1.4 bibtex_0.4.2.2
[81] Rdpack_0.11-1 SDMTools_1.1-221.2
[83] rlang_0.4.2 pkgconfig_2.0.3
[85] bitops_1.0-6 lattice_0.20-38
[87] ROCR_1.0-7 purrr_0.3.3
[89] htmlwidgets_1.5.1 cowplot_1.0.0
[91] tidyselect_0.2.5 RcppAnnoy_0.0.14
[93] plyr_1.8.5 magrittr_1.5
[95] R6_2.4.1 gplots_3.0.1.2
[97] multcomp_1.4-12 pillar_1.4.3
[99] sn_1.5-4 fitdistrplus_1.0-14
[101] survival_3.1-8 tibble_2.1.3
[103] future.apply_1.4.0 tsne_0.1-3
[105] crayon_1.3.4 utf8_1.1.4
[107] KernSmooth_2.23-16 plotly_4.9.1
[109] progress_1.2.2 grid_3.6.2
[111] data.table_1.12.8 metap_1.2
[113] digest_0.6.23 tidyr_1.0.0
[115] numDeriv_2016.8-1.1 R.utils_2.9.2
[117] RcppParallel_4.4.4 munsell_0.5.0
[119] viridisLite_0.3.0