只接收独特的警告信息
Only receive unique warning messages
警告消息是我想知道的一个很好的信息。但我只想知道一次!
所以这个函数会抛出 2 个不同的警告并重复 20 次。
我如何告诉 R 只打印独特的警告。我正在寻找通用解决方案。
Warning messages:
1: NAs introduced by coercion
2: In sqrt(-1) : NaNs produced
这是我的例子:
foobar <- function(n=20) {
for (i in 1:n) {
as.numeric("b")
sqrt(-1)
}
}
foobar()
要return只有唯一的警告字符串,请使用
unique(warnings())
现在,您可能遇到的问题是您的函数有超过 50 个警告,在这种情况下 warnings()
将无法捕获所有警告。要解决此问题,您可以将选项中的 nwarnings
增加到例如help page of warnings.
中建议的 10000
options(nwarnings = 10000)
示例:
foobar <- function(n=20) {
warning("First warning")
for (i in 1:n) {
as.numeric("b")
sqrt(-1)
}
warning("Last warning")
}
foobar(60)
unique(warnings())
## Warning messages:
## 1: In foobar(60) : First warning
## 2: NAs introduced by coercion
## 3: In sqrt(-1) : NaNs produced
op <- options(nwarnings = 10000)
foobar(60)
unique(warnings())
## Warning messages:
## 1: In foobar(60) : First warning
## 2: NAs introduced by coercion
## 3: In sqrt(-1) : NaNs produced
## 4: In foobar(60) : Last warning
options(op)
警告消息是我想知道的一个很好的信息。但我只想知道一次!
所以这个函数会抛出 2 个不同的警告并重复 20 次。
我如何告诉 R 只打印独特的警告。我正在寻找通用解决方案。
Warning messages:
1: NAs introduced by coercion
2: In sqrt(-1) : NaNs produced
这是我的例子:
foobar <- function(n=20) {
for (i in 1:n) {
as.numeric("b")
sqrt(-1)
}
}
foobar()
要return只有唯一的警告字符串,请使用
unique(warnings())
现在,您可能遇到的问题是您的函数有超过 50 个警告,在这种情况下 warnings()
将无法捕获所有警告。要解决此问题,您可以将选项中的 nwarnings
增加到例如help page of warnings.
options(nwarnings = 10000)
示例:
foobar <- function(n=20) {
warning("First warning")
for (i in 1:n) {
as.numeric("b")
sqrt(-1)
}
warning("Last warning")
}
foobar(60)
unique(warnings())
## Warning messages:
## 1: In foobar(60) : First warning
## 2: NAs introduced by coercion
## 3: In sqrt(-1) : NaNs produced
op <- options(nwarnings = 10000)
foobar(60)
unique(warnings())
## Warning messages:
## 1: In foobar(60) : First warning
## 2: NAs introduced by coercion
## 3: In sqrt(-1) : NaNs produced
## 4: In foobar(60) : Last warning
options(op)