r - 在循环中读取 R 中的 XML 文件崩溃
问题描述
我有一个循环遍历 xml 文件列表并处理它们的代码。当我为单个 xml 执行代码时,结果是预期的。但是当我开始循环时,不同的文件中会出现意外错误。错误的文件在每次迭代中都会更改,因此没有模式可以找到错误。
前任。单个文件:
p_xml <- function(file)
{
tmp<-tryCatch(
{
(read_xml(path_XML))
},error=function(e)
{
return(NA)
})
if(is.na(tmp))
{
file <- read_xml(path_XML, encoding = "ISO-8859-1")
}else{
file <- tmp
}
id <- as.numeric(xml_attr(file, "id"))
year_id <- as.numeric(xml_attr(file, "machine_year"))
....
return(data)
}
此代码以正确的方式返回 data.table。但是如果我在一个循环中执行这个函数:
global_dt<-data.table()
for(j in 1:length(file_names))
{
current_file <- file_names[j]
f <- p_xml(file.path(current_dir,current_file))
global_dt<-rbind(global_dt,f)
}
我收到这样的错误:
- doc_parse_file 中的错误(con,encoding = encoding,as_html = as_html,options = options):无法解析 /path/file.xml *
事实是,如果我随后使用失败的文件执行单个代码,它会返回我所期望的。我使用 xml2 库来读取文件
解决方案
试试这个工作流程
library(data.table)
#store the result of each run of the function into a list
l <- lapply( list_files, p_xml )
#rowbind the list together into one data.table
global_dt <- data.table::rbindlist( l )
推荐阅读
- javascript - 结合 await 和 Promise.all 在我的 node.js 微服务中不起作用
- angular-dynamic-components - 动态组件未加载到专利组件内
- java - Android:调整软键盘不起作用
- node.js - 文本文件中的节点js输入值
- hyperledger-fabric - 使用版本 1.4 的 Hyperledger Fabric 客户端 SDK 时出错
- scala - 如何根据数据类型在 Spark Dataframe 中动态更改列数据类型
- javascript - 如何将 PDF 嵌入 Firefox 的 html 页面的一部分
- vue.js - Vuetify 与 3rd 方表单组件 - 如何像 v-text-field 一样设置样式
- ruby-on-rails - 无法通过 Bundler 安装 gem。偏僻的: !偏僻的: !Push 被拒绝,无法编译 Ruby 应用程序。远程:远程:!推送失败
- javascript - 通过循环构建 JSON 数组