R 是一種在數據分析與統計計算領域廣泛使用的編程語言。其關鍵優勢之一是能夠生成高質量的報告和文檔,這些報告和文檔可以使用 RMarkdown 輕松定制和更新。在本文中,我們將探討使用 R 從 RMarkdown 文件生成.pdf 文件
1.生成方法
新建Rmarkdown:
File > New File > RMarkdown
?
在編輯完后選擇Knit?的Knit to pdf就可以輸出pdf文檔
R會自動打開默認pdf閱讀器展示生成的PDF:
2.可能的報錯及解決:
(1)Latex error
在首次使用的時候,如果電腦并沒有latex,會輸出報錯,我們通過按照內置latex解決:
install.packages("tinytex")
(2)Encoding errors
如果 RMarkdown 文件包含非 ASCII 字符,例如重音符號或特殊字符,在生成 PDF 時可能會遇到編碼錯誤。為了排除編碼錯誤,可以嘗試將 RMarkdown 文件的編碼設置為 UTF-8 或其他兼容編碼。
從:
---
title: "hw5"
author: "Hu_zhuocheng"
date: "2025-04-27"
output: pdf_document
---
改為:
---
title: "hw5"
author: "Hu_zhuocheng"
date: "2025-04-27"
output: pdf_document
encoding: UTF-8
---
?也可以在 R Markdown 文件的開頭添加一個 R 代碼塊,用于設置默認的字符串編碼為 UTF-8
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
options(encoding = "UTF-8")
```
?
(3)Unicode character Error
Rmarkdown可以將R文檔轉換為網頁、word、pdf格式,但是我們發現一個文檔轉網頁和word都可以轉換,但是pdf就會報錯,如下:
output file: hw5.knit.md! LaTeX Error: Unicode character ρ (U+03C1)not set up for use with LaTeX.Try other LaTeX engines instead (e.g., xelatex) if you are using pdflatex. See https://bookdown.org/yihui/rmarkdown-cookbook/latex-unicode.html
錯誤: LaTeX failed to compile hw5.tex. See https://yihui.org/tinytex/r/#debugging for debugging tips. See hw5.log for more info.
停止執行
這是因為文檔中含有一些數學字符,希臘字母導致的。?
我們通過更改頭信息選擇pdf編輯器:
?將:
---
title: "hw5"
author: "Hu_zhuocheng"
date: "2025-04-27"
output: pdf_document
---
改為:
---
title: "hw5"
author: "Hu_zhuocheng"
date: "2025-04-27"
output:pdf_document:latex_engine: xelatexword_document: defaulthtml_document:df_print: paged
---
如果還有其他問題歡迎評論區討論!