在R中使用mclapply抑制警告

thu*_*oom 8 warnings r mclapply

随着mclapply()所有发出的警告似乎得到抑制:

library(multicore) 
mclapply(1:3, function(x) warning(x))
[[1]]
[1] "1"

[[2]]
[1] "2"

[[3]]
[1] "3"
Run Code Online (Sandbox Code Playgroud)

同时lapply会给:

lapply(1:3, function(x) warning(x))
[[1]]
[1] "1"

[[2]]
[1] "2"

[[3]]
[1] "3"

Warning messages:
1: In FUN(1:3[[3L]], ...) : 1
2: In FUN(1:3[[3L]], ...) : 2
3: In FUN(1:3[[3L]], ...) : 3
Run Code Online (Sandbox Code Playgroud)

有关如何避免丢失警告的任何提示?

top*_*ito 5

根据mclapply的帮助页面,我认为该参数mc.silent应该允许您选择是否打印警告。奇怪的是,它并没有这样做。将其明确设置为TRUEFALSE不会对您的情况产生任何影响。

因此,我们只剩下一个有点肮脏的黑客:强制 R 在警告发生时打印警告。

options(warn=1)
mclapply(1:3, function(x) warning(x))

# Warning in FUN(1L[[1L]], ...) : 1
# Warning in FUN(2L[[1L]], ...) : 2
# Warning in FUN(3L[[1L]], ...) : 3
# [[1]]
# [1] "1"
#
# [[2]]
# [1] "2"
#
# [[3]]
# [1] "3"
Run Code Online (Sandbox Code Playgroud)

  • 请注意,这在 GUI 或 RStudio 中不起作用。但文档明确警告不要将“mclapply”与这些一起使用。 (2认同)