Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set different global options in knitr and RStudio for word and html?

Tags:

r

rstudio

knitr

I am using RStudio 0.98.932 and knitr 1.6. Would like to set different global knitr options for word and html. For example, want to set fig.width and fig.height as 6 for word and 11 for html.

I can write some codes to switch the setting if it is available for the output format of a rmd file. How should I do this? Thanks for any suggestions.

like image 437
Bangyou Avatar asked Aug 11 '14 06:08

Bangyou


People also ask

How do I convert RMD to HTML in R?

To transform your markdown file into an HTML, PDF, or Word document, click the “Knit” icon that appears above your file in the scripts editor. A drop down menu will let you select the type of output that you want. When you click the button, rmarkdown will duplicate your text in the new file format.

What does knitr :: Opts_chunk set echo true mean?

The first code chunk: ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` is used to specify any global settings to be applied to the R Markdown script. The example sets all code chunks as “echo=TRUE”, meaning they will be included in the final rendered version.

How do you use the knitr in RStudio?

If you are using RStudio, then the “Knit” button (Ctrl+Shift+K) will render the document and display a preview of it.

How do I change the working directory in R Markdown?

The usual way to change the working directory is setwd() , but please note that setwd() is not persistent in R Markdown (or other types of knitr source documents), which means setwd() only works for the current code chunk, and the working directory will be restored after this code chunk has been evaluated.


1 Answers

Try putting this code chunk at the beginning of the Rmd document.

```{r setup, cache=FALSE, include=FALSE}
library(knitr)
output <- opts_knit$get("rmarkdown.pandoc.to")
if (output=="html") opts_chunk$set(fig.width=11, fig.height=11)
if (output=="docx") opts_chunk$set(fig.width=6,  fig.height=6)
```

One of the package options returned by opts_knit$get() is markdown.pandoc.to. This is evidently set to "html", "docx", or "latex" depending on the chosen output format (HTML, Word, or PDF). So you can test that and set the chunk options fig.width and fig.height accordingly.

like image 162
jlhoward Avatar answered Oct 18 '22 04:10

jlhoward