r - 错误函数内的变量声明
问题描述
我在函数的错误函数中有一个变量声明tryCatch
。但是当错误触发时,即使成功输出了错误信息,也不会执行变量声明。
tryCatch({ var_binned_names = arules::discretize(Xt,
method = arules_method,
breaks = num_breaks,
ordered = TRUE)
}, error = function(error) {
cat("Error: could not discretize numeric", numeric_i, "", name, "\n")
cat("Unique values:", length(unique(Xt)), "\n")
var_binned_names = Xt
})
人们会期望,当var_binned_names
由于离散化错误而无法分配时,它将Xt
在错误函数中分配。但是,发生的情况是它没有定义。
解决方案
使用这种方法:
Xt <- 1
res <- tryCatch({ stop("some error")
}, error = function(error) {
cat("some error message")
Xt
})
res
#[1] 1
tryCatch
有返回值。它是表达式的返回值或(如果触发了错误等条件)处理程序的返回值。
推荐阅读
- sql - 显示缺失的行(oracle、sql)
- java - JNI_CreateJavaVM:OpenBSD 上的“无法为代码缓存保留足够的空间”
- html - 我的 html 5 视频似乎在 0.5 秒后停止
- lync - Skype Web SDK - 找不到此配置的包定义
- django - PyInstaller(或其他工具)可以从 Django 项目为生产环境创建可执行文件吗?
- kubernetes - 如何通过 initContainer 使用私有存储库
- vue.js - Vue js不断返回“未知的自定义元素”
- excel - 即使 Application.ScreenUpdating 为 False,屏幕也会闪烁
- javascript - 回调 ES 2016 类定义时如何使用 `this=self` 类
- python - 我的 GitHub 示例代码中没有“manage.py”文件