Shiny渲染Flexdashboard格式Rmd时出现pandoc错误1如何解决?
报错触发原因
- 核心原因是编码不匹配:该错误多出现在Windows系统环境下,系统默认编码为GBK/GB2312,而pandoc转换文档时强制要求内容为UTF-8编码。
- flexdashboard与普通
html_output的渲染逻辑差异:flexdashboard会将所有依赖的CSS、字体、JS资源全部内联到最终HTML文件中,内联过程中如果R的写入编码没有设置为UTF-8,就会生成包含非UTF-8字节的中间文件,触发pandoc解码失败。而普通html_output对编码的容错率更高,且默认不会内联全部依赖资源,因此不会触发报错。 - 你提供的RMD文件YAML头存在缩进错误,flexdashboard对YAML格式校验更严格,格式错误会导致元数据解析异常,也可能生成乱码内容触发编码报错。
可行解决建议
- 修正RMD的YAML头缩进,正确格式如下:
--- title: "Render RMD" date: "`r format(Sys.Date(),'%d %B %Y')`" output: flexdashboard::flex_dashboard: theme: cosmo ---
- 调用
rmarkdown::render时强制指定编码,修改Shiny中渲染部分的代码为:
rmarkdown::render( 'mpg_ex.rmd', envir = new.env(), output_file = paste('RenderRMD_usingShiny_', as.Date(data.table::as.IDate(Sys.Date())),'_', strftime(Sys.time(),format="%I%M%S%p"),'.html', sep=""), encoding = "UTF-8", options = list(pandoc_args = c("--encoding", "UTF-8")) )
- 在Shiny代码开头添加全局编码设置:
options(encoding = "UTF-8") # 中文Windows系统使用下面这行,英文系统替换为 "English.UTF-8" Sys.setlocale("LC_ALL", "Chinese.UTF-8")
- 确认RMD文件本身的保存编码为UTF-8:用RStudio或记事本打开mpg_ex.rmd,选择另存为,编码项选择UTF-8覆盖原文件即可。
- 若上述操作仍未解决,可关闭flexdashboard的资源内联配置,在YAML中添加
self_contained: false参数:
--- title: "Render RMD" date: "`r format(Sys.Date(),'%d %B %Y')`" output: flexdashboard::flex_dashboard: theme: cosmo self_contained: false ---
内容的提问来源于stack exchange,提问作者BharatAyya
相关产品推荐
相关产品推荐

