R: Конвертируйте Rmarkdown в PDF

#r #pdf #r-markdown

Вопрос:

Я работаю с языком программирования R. Я учусь конвертировать «rmarkdown» в pdf с помощью Rstudio. Я следую этому уроку здесь: https://rmarkdown.rstudio.com/articles_intro.html

Я впервые создал новый файл Rmarkdown:

введите описание изображения здесь

Затем я ввел следующий текст в редактор Rmarkdown:

 ---
output: html_document
---

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see .

When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

```{r}
summary(cars)
```

You can also embed plots, for example:

```{r, echo=FALSE}
plot(cars)
```

Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
 

введите описание изображения здесь

Затем я нажал «Связать в PDF».:

введите описание изображения здесь

But this did not work and returned the following message:

 processing file: testfile.Rmd
  |..........                                                            |  14%
  ordinary text without R code

  |....................                                                  |  29%
label: setup (with options) 
List of 1
 $ include: logi FALSE

  |..............................                                        |  43%
  ordinary text without R code

  |........................................                              |  57%
label: cars
  |..................................................                    |  71%
  ordinary text without R code

  |............................................................          |  86%
label: pressure (with options) 
List of 1
 $ echo: logi FALSE

  |......................................................................| 100%
  ordinary text without R code


output file: testfile.knit.md

"C:/Program Files/RStudio/bin/pandoc/pandoc"  RTS -K512m -RTS testfile.utf8.md --to latex --from markdown autolink_bare_uris tex_math_single_backslash --output testfile.tex --lua-filter "C:UsersmeOneDriveDocumentsRwin-library4.0rmarkdownrmarkdownluapagebreak.lua" --lua-filter "C:UsersmeOneDriveDocumentsRwin-library4.0rmarkdownrmarkdownlualatex-div.lua" --self-contained --highlight-style tango --pdf-engine pdflatex --variable graphics --variable "geometry:margin=1in" 
Error: LaTeX failed to compile testfile.tex. See https://yihui.org/tinytex/r/#debugging for debugging tips.
In addition: Warning messages:
1: In has_crop_tools() : 
Tool(s) not installed or not in PATH: pdfcrop, ghostcript
-> As a result, figure cropping will be disabled.
2: In system2(..., stdout = if (use_file_stdout()) f1 else FALSE, stderr = f2) :
  '"pdflatex"' not found
Execution halted

No LaTeX installation detected (LaTeX is required to create PDF output). You should install a LaTeX distribution for your platform: https://www.latex-project.org/get/

  If you are not sure, you may install TinyTeX in R: tinytex::install_tinytex()

  Otherwise consider MiKTeX on Windows - http://miktex.org

  MacTeX on macOS - https://tug.org/mactex/
  (NOTE: Download with Safari rather than Chrome _strongly_ recommended)

  Linux: Use system package manager
 

Может кто-нибудь, пожалуйста, показать мне, что я делаю не так? Есть ли простой способ конвертировать Rmarkdown в PDF?

Спасибо

Примечание: Информация о сеансе

 > sessionInfo()
R version 4.0.3 (2020-10-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19043)

Matrix products: default

locale:
[1] LC_COLLATE=English_Canada.1252  LC_CTYPE=English_Canada.1252   
[3] LC_MONETARY=English_Canada.1252 LC_NUMERIC=C                   
[5] LC_TIME=English_Canada.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
 [1] compiler_4.0.3    htmltools_0.5.1.1 tools_4.0.3       yaml_2.2.1       
 [5] tinytex_0.30      rmarkdown_2.7     knitr_1.31        digest_0.6.27    
 [9] xfun_0.21         rlang_0.4.10      evaluate_0.14  
 

Комментарии:

1. Сделайте это: install.packages('tinytex') и tinytex::install_tinytex() строка за строкой, затем перезапустите R и RStudio и скажите мне.

2. @ TarJae : спасибо за ваш ответ! Я попробовал это и получил следующую ошибку:

3. Ошибка: LaTeX не удалось скомпилировать tesst.tex. Видишь yihui.org/tinytex/r/#debugging для советов по отладке. Кроме того: Предупреждающие сообщения: 1: В has_crop_tools() : Инструмент(ы) не установлен или не указан в ПУТИ: pdfcrop, ghostcript -> В результате обрезка рисунка будет отключена. 2: В system2(…, stdout = if (use_file_stdout()) f1 еще ЛОЖЬ, stderr = f2) : «pdflatex» не найден Выполнение остановлено

4. ОК. Установите Rtools < cran.r-project.org/bin/windows/Rtools > ВАЖНО: Вы должны убедиться, что флажок установлен, чтобы установщик изменил ваш ПУТЬ, затем установите devtools с помощью > install.packages("devtools") . затем повторите то же самое 1. install.packages('tinytex') затем 2. tinytex::install_tinytex()

5. Попробуйте изменить output: html_document output: pdf_document , если вы хотите связать в формате pdf, а не в формате html.