R Markdown通过knitr和pandoc转成HTML出现错误代码137。

5
我有以下问题:我有一个.Rmd文件,通过使用Rstudio按钮的knitr + pandoc编译它成html格式。 在这个.Rmd文件中,我按照这里描述的方法将json数据传递到js层。
这是因为我想为一些自定义d3可视化使用数据。 对于适量的数据,这似乎运行良好,但是当我尝试传入更大的数据时,从.Rmd编译到html时出现问题;问题似乎与pandoc有关,因为我得到了以下错误信息: pandoc文档转换失败,错误代码137
我尝试在网上寻找有关此错误消息的解释,但没有什么进展。是否有任何人知道这个错误的含义?

不是相同的错误信息,但这可能有帮助:https://dev59.com/tFsW5IYBdhLWcg3wsY9P - Stedy
2
可能是内存不足错误。请参见 https://dev59.com/iXNA5IYBdhLWcg3wPLP-。 - HappyFace
对我来说,肯定是记忆力不足。 - undefined
1个回答

1

经过研究,我仍然无法修复错误。但是,我有一个解决方法,可以让您将任意json数据注入到使用R Markdown生成的html报告中,而无需完全通过pandoc进行;后者似乎不喜欢使用例如描述的方法注入大量json。

http://livefreeordichotomize.com/2017/01/24/custom-javascript-visualizations-in-rmarkdown/

由于这个137错误似乎与pandoc终止转换过程的时间过长有关。

解决方法很简单:不要在knitr编译步骤中使用“asis”选项将json数据注入代码块中(如上面链接所述),而是最好将json数据附加到通过knitr和pandoc编译产生的html文件末尾。换句话说,将json数据注入kitr + pandoc步骤输出的html文件中。

假设要编译为html的rmd文件位于已安装软件包中,并遵循以下建议:

嵌入任意JSON的最佳实践?

使用xml2软件包和如下函数即可实现此目标:

create_report <- function(file, 
                          subdir, 
                          package, 
                          parameters, 
                          output_file, 
                          data_arr = NULL){
  #check file exists
  if (system.file(package = package, subdir, file) == ''){
    stop('Cannot find the .rmd file')
  }
  #first generate report
  address <- rmarkdown::render(system.file(package = package,
                                       subdir,
                                       file),
                           output_dir = getwd(),
                           intermediates_dir = getwd(),
                           output_file = output_file,
                           params = parameters,
                           clean = FALSE)
  #then append the data in the json files located in the named list
  #data_arr directly into the 
  #html after compilation if needed:
  if (!is.null(data_arr)){
  report <- xml2::read_html(address)
  report_body <- xml2::xml_find_first(report, "body")
  #adding the data
  for (i in 1:length(data_arr)){
    xml2::xml_add_child(report_body, "script", type = 'application/json', id = 
  names(data_arr[i]), data_arr[[i]])
  }
  #Then add a script that takes the data from the script tags added above and 
  #initializes the variables.
  varnames <- paste0("var ", names(data_arr), " = 
  JSON.parse(document.getElementById('", names(data_arr), "').innerHTML);",
                   collapse = " ")
  xml2::xml_add_child(report_body, "script", type = 'text/javascript', id = 
  'external_json_init', varnames)
  xml2::write_html(report, address)
}
return(address)
}

在上述函数中,data_arr 应该是一个命名列表,其元素是通过将 R 对象转换为 json 字符串而获得的,例如使用 jsonlite::toJSON,其名称是要用于在 javascript 层中存储数据的变量名称。通过这种方式,任意大小的 json 可以被注入到由 R markdown 生成的 html 中,以便由 javascript 进行操作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接