Car*_*lli 41 latex r knitr r-markdown
在knitr中,size选项在.Rnw文件中正常工作,以下代码生成:
\documentclass{article}
\begin{document}
<<chunk1, size="huge">>=
summary(mtcars)
@
\end{document}
Run Code Online (Sandbox Code Playgroud)

但是,我不能让它在Rmarkdown中工作.以下代码不会像在.rnw文件中那样更改字体大小.尝试设置选项时会发生同样的事情opts_chunk$set(size="huge").
这是预期的行为吗?如何更改块代码字体大小?(我的意思是使用knitr选项,而不是\huge在代码之前添加)
---
title: "Untitled"
output: pdf_document
---
```{r, size="huge"}
summary(mtcars)
```
Run Code Online (Sandbox Code Playgroud)

我使用的是RStudio版本0.98.987,knitr 1.6和rmarkdown 0.2.68.
Mar*_*zer 24
提出修改knitr钩子的想法,我们可以做到以下几点:
def.chunk.hook <- knitr::knit_hooks$get("chunk")
knitr::knit_hooks$set(chunk = function(x, options) {
x <- def.chunk.hook(x, options)
ifelse(options$size != "normalsize", paste0("\n \\", options$size,"\n\n", x, "\n\n \\normalsize"), x)
})
Run Code Online (Sandbox Code Playgroud)
此代码段修改默认的块挂钩.它只是检查块选项大小是否不等于其默认值(normalsize),如果是,则将值预先设置options$size为代码块的输出(包括源!)并附加\\normalsize以便切换回来.
因此,如果要添加size="tiny"到块,那么此块生成的所有输出都将以这种方式打印.
您所要做的就是将此代码段包含在文档的开头.
Geo*_*sky 16
\tiny
```{r}
summary(mtcars)
```
\normalsize
Run Code Online (Sandbox Code Playgroud)
可用的降序大小选项有:
Huge> huge> LARGE> Large> large> normalsize> small> footnotesize> scriptsize>tiny
Tom*_*Tom 10
根据这个要点,你必须使用css定义字体大小:
<style type="text/css">
body, td {
font-size: 14px;
}
code.r{
font-size: 20px;
}
pre {
font-size: 20px
}
</style>
Run Code Online (Sandbox Code Playgroud)
code.r将控制从代码块回显的R代码的字体大小,同时pre将应用于代码的任何R结果输出.
完整的.Rmd文件可能如下所示:
---
title: "FontTest"
author: "Thomas Hopper"
date: "January 13,2016"
output: html_document
---
<style type="text/css">
body, td {
font-size: 14px;
}
code.r{
font-size: 20px;
}
pre {
font-size: 20px
}
</style>
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
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 <http://rmarkdown.rstudio.com>.
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 cars}
summary(cars)
```
Run Code Online (Sandbox Code Playgroud)
生成的html呈现为:
您可以通过从包中导出基于以下函数的内容来定义自己的文档格式my_package:
my_report <- function(...) {
fmt <- rmarkdown::pdf_document(...)
fmt$knitr$knit_hooks$size = function(before, options, envir) {
if (before) return(paste0("\n \\", options$size, "\n\n"))
else return("\n\n \\normalsize \n")
}
return(fmt)
}
Run Code Online (Sandbox Code Playgroud)
这将定义一个knitr chunk hook size,它将在块之前和块\normalsize之后放置相应的latex命令.
无论如何,通过以下R降价,您可以检查它是否正常工作:
---
output: my_package::my_report
---
Test text for comparison
```{r}
print(1)
```
The next code chunk has `size = 'tiny'` in the chunk options.
```{r, size = 'tiny'}
print(1)
```
Run Code Online (Sandbox Code Playgroud)
我从`markdown :: render()得到以下结果:
另请参阅我在github上打开的问题:
https://github.com/yihui/knitr/issues/1296