用R自动生成pdf文件

1)安装R程序包knitr,写markdown,需要安装生成pdf的工具MikTex,RTools(RTools 需要安装吗?待验证)

安装 R package — rmarkdown,

Yaml Header参数

this is yaml header 

生成pdf的Rmd文件中,设定 "output: pdf_document"

YAML header将决定如何展现你的 .Rmd file.文件,用两个 --- 包围,如下图:

---
title: "test"
author: "dym"
date: "2017年10月10日"
output: pdf_document
---

output: 选择其中一种类型的文件类型,html_document   pdf_document   word_document

Rmd插入R语句

knitr包能够兼容markdown语法,尤其包含执行R代码的能力,Rmd文件中插入R语句:

echo=FALSE  表示不打印命令语句

eval=FALSE   表示不显示运行结果

```{r pressure, echo=FALSE, eval=FALSE}
plot(pressure)
```

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

改变plot生成的图片大小的参数,fig.width=11,11为英寸值,改变fig.width,可改变生成的图片的宽度

行间代码

嵌入R代码到文本当中,在代码的两侧用点’来包围,如下图:

Two plus two equals `r 2 + 2`.

显示结果为:

Two plus two equals 4.

 Render文件格式转换

rmarkdown::render() 将RMD文件转换为html 或 pdf文件:

library(rmarkdown)
render('test2.Rmd', pdf_document(latex_engine = 'xelatex'), output_file = 'test_haha.pdf')
render('1-example.Rmd', output_file = 'haha.html')

knitr  markdown  转换成pdf   

http://www.dataguru.cn/thread-208296-1-1.html

中文字符的问题

在rmd文件中,如果有中文字符,运行文件的时候会报错;

如果rmd文件中打印一个变量,变量的值是中文字符,转换为pdf文件时也是乱码;用plot画图时,如果坐标的刻度标签或标题(参数main)有中文字符,输出在pdf文档中也是乱码;

1)对于输出变量是中文的情况:

可以通过在rmd的yaml文件中加入下面字段,实现在pdf中正常输出中文:

 header-includes:

- usepackage{xeCJK}

2)对于横坐标的刻度标签含中文的情况,解决方案是在plot函数中,设置xaxt = 'n',用axis函数设置坐标刻度,用text函数加上刻度标签,标签中不能含中文字符,这样横坐标就可以正常显示了;

原文地址:https://www.cnblogs.com/thinkers-dym/p/8127508.html