在研究了错误之后,我仍然无法修复它。但是,我有一种解决方法,它允许将任意 json 数据注入使用 R markdown 生成的 html 报告中,而无需通过 pandoc;后者似乎不喜欢使用例如注入大量 json。
中描述的方法
http://livefreeordichotomize.com/2017/01/24/custom-javascript-visualizations-in-rmarkdown/
因为在我看来这个 137 错误与 pandoc 终止转换为 html 的过程有关,因为它需要很长时间才能终止。
解决方法非常简单:与其在 knitr 编译步骤中通过将 json 数据包含在带有 'asis' 选项的块中(如上述链接中所述)来注入 json 数据,不如将 json 数据附加到通过knitr和pandoc编译生成的html文件中的结尾。也就是说,在kitr + pandoc步骤的输出html文件中注入json数据。
假设要编译成 html 的 rmd 文件位于已安装的包中,并遵循
处的建议
Best practice for embedding arbitrary JSON in the DOM?
为了在 DOM 中嵌入 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应该是一个命名列表,其元素是json字符串,例如通过使用jsonlite::toJSON转换R对象,其名称是用于存储数据的变量名javascript层。
通过这种方式,可以将任意大小的 json 注入到 R markdown 生成的 html 中,由 javascript 进行操作。