r - 显示由 R 脚本生成的警告发生时

标签 r

我有一个包含多个块的脚本,其中的行看起来像这样......

#Read data for X
DataX = read.delim(file = 'XRecords.txt',
                   col.names = XFields[,'FieldName'])
print('Data X read')
#Convert fields that should be numeric into numeric so they can summed
DataX[,NumFieldNames] = as.numeric(as.character(XData[,NumFieldNames]))
print('Data X scrubbed')

当我获取脚本时,我得到这样的输出......
[1] "Data X read"
[1] "Data X scrubbed"
[1] "Data Y read"
[1] "Data Y scrubbed"
Warning message:
In eval(expr, envir, enclos) : NAs introduced by coercion

根据该输出,我重新加载数据 Y 并开始查找字符串到数字转换失败的记录。经过几个小时的挫折,我意识到数据 X 实际上是有类型转换错误的那个。

看起来正在发生的事情是引发了警告,但在脚本完成之前它不会显示在控制台上。有没有办法在警告一出现就将警告输出到控制台?我试过flush.console(),但它似乎对警告不起作用。

如果可以避免,我宁愿不要在我的系统上加载任何额外的包。我正在使用它来工作,为了在我的计算机上安装 CRAN 发行版,我不得不跳过几个环节。

谢谢你。我很感激你的帮助。

最佳答案

让我们举一个例子来说明问题

foo <- function() {
  X <- c("1", "2", "three")
  print("Data X read")
  X <- as.numeric(X)
  print("Data X scrubbed")
  Y <- c("1", "2", "3")
  print("Data Y read")
  Y <- as.numeric(Y)
  print("Data Y scrubbed")
}

如果运行(甚至以交互方式),您看到的行为就会出现
> foo()
[1] "Data X read"
[1] "Data X scrubbed"
[1] "Data Y read"
[1] "Data Y scrubbed"
Warning message:
In foo() : NAs introduced by coercion

警告的行为由 warn 处理选项(见 help("options"))。这给出了选择,包括

If warn is one, warnings are printed as they occur.



将选项更改为 1 然后给出
> options(warn=1)
> foo()
[1] "Data X read"
Warning in foo() : NAs introduced by coercion
[1] "Data X scrubbed"
[1] "Data Y read"
[1] "Data Y scrubbed"

关于r - 显示由 R 脚本生成的警告发生时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15439336/

相关文章:

r - 仅使用非 NA 单元格替换另一列中的单元格

r - 如何使用 R 中的 read.table 读取\"双引号转义值

r - 如何在 R 图中更改 Xlab、Ylab 和 XY 轴颜色和字体大小的值

r - 在 R 中进行条件运行总计的更有效方法

替换/修改逻辑向量中的值(模式匹配)

r - 如何在R中使用查找表而不创建重复项?

r - 在 R 中将列表作为长格式的列的 tibble?

r - 将 textGrob 转换为 imageGrob/rasterGrob?

r - 在 R 中将错误消息捕获为字符串

r - 在 R 中为当前日期创建年/周格式