formatting/styling a docx using Rmarkdown - r-markdown

I am trying to style the word document using the Rmarkdown. I have successfully applied the basic styles by providing the reference word document under the YAML.
However, I am looking at some advanced styling like applying the different font size or colour to the paragraphs/headers in the same document.
Right now if I change the colour of any one paragraph to blue, colour of all the paragraphs get's changed to blue where I wanted to change the colour of only some of the paragraphs.
current rmarkdown:
---
title: "`r params$report_title`"
params:
report_title: NA
absolute_application_path: NA
output:
word_document:
md_extensions: +styles
reference_docx: "mmr_tec_report_reference-file.docx"
---
```{r setup, include=FALSE, echo=FALSE}
knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE)
library(pander)
```
```{r echo = FALSE}
application_path = params$absolute_application_path
signature_note <- ""
summary_note <- ""
```
## Template Instructions:
::: {custom-style="MMR_BodyText"}
The blue text are instructions or guidance for preparing the Sample or examples. Delete the blue highlighted instructions as the document is being drafted.
:::
Am I doing anything wrong up there?
I would like to know if there is any way to get it worked?

Related

Maximize imported image on page in officer / officedown to Word (docx)

I recently tried using officedown to create a .docx report of my document. In my documents I import images from an \images folder in my project directory.
Normally when I knit a document I am able to maximize its position on the page.
Does anyone know how to do this using officedown? I have no issues when I run this code in RMarkdown
This is what I get using officedown
This is what I want (notice the image is taking up the whole page)
I have included a reprex below
---
date: "`r Sys.Date()`"
author:
title: "GitHub Example"
output:
officedown::rdocx_document
---
```{r setup, include=FALSE, echo = FALSE}
pacman::p_load(readxl, dplyr, apastats, officedown, officer, ggplot2, knitr) # load packages
knitr::opts_chunk$set(fig.align = 'center',
fig.cap = TRUE,
fig.pos = 'H',
fig.path = 'images/',
echo = FALSE,
warning = FALSE,
message = FALSE,
include = TRUE,
out.height="100%", out.width="100%",
dpi = 300)
```
```{r}
# Creating a boxplot and saving it in \images directory
plot <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
geom_boxplot()
ggsave("images/plot.png",plot, width=11, height=8.5, dpi=300)
```
## Figures
Figure \#ref(fig:boxplot) shows a boxplot that is made within the RMarkdown document.
I want to call in an image saved from a previous R scripts which is saved
in my `\images` directory shown in Figure \#ref(fig:plot). But notice how it
does not take up the whole page.
<!---BLOCK_LANDSCAPE_START--->
```{r fig.cap="A boxplot", fig.id = "boxplot"}
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
geom_boxplot()
```
<!---BLOCK_LANDSCAPE_STOP--->
<!---BLOCK_LANDSCAPE_START--->
```{r fig.id="plot", fig.cap="boxplot imported from images folder", echo=FALSE}
knitr::include_graphics("images/plot.png")
```
<!---BLOCK_LANDSCAPE_STOP--->
You can use knitr usual parameters fig.width and fig.height (inches).
---
date: "`r Sys.Date()`"
author:
title: "GitHub Example"
output:
officedown::rdocx_document
---
```{r setup, include=FALSE, echo = FALSE}
pacman::p_load(readxl, dplyr, apastats, officedown, officer, ggplot2, knitr) # load packages
knitr::opts_chunk$set(fig.align = 'center',
echo = FALSE,
warning = FALSE,
message = FALSE,
dpi = 300)
```
```{r}
plot <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
geom_boxplot()
```
<!---BLOCK_LANDSCAPE_START--->
```{r fig.cap="A boxplot", fig.id = "boxplot"}
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
geom_boxplot()
```
```{r fig.width=10, fig.height=5, fig.id="plot", fig.cap="boxplot imported from images folder", echo=FALSE}
plot
```
<!---BLOCK_LANDSCAPE_STOP--->
Tips for working with plots/figures in Word output:
a) you need to use fig.height and/or fig.width to scale plots/figures;
b) consider using chunk option crop = TRUE with the function hook_pdfcrop() to trim/crop the extra white margin around the plot (see #CL. SO answer here);
c) chunk options: fig.align, fig.pos, out.height, out.width or out.extra are not supported for Word output.
To achieve desired output, you may consider the following changes:
```{r setup, include = FALSE, echo = FALSE}
pacman::p_load(readxl, dplyr, apastats, officedown, officer, ggplot2, knitr) # load packages
knitr::opts_chunk$set(fig.cap = TRUE,
fig.path = 'images/',
echo = FALSE,
warning = FALSE,
message = FALSE,
include = TRUE,
dpi = 300)
```
```{r}
# Creating a boxplot and saving it in \images directory
plot <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
geom_boxplot()
ggsave("images/plot.png", plot, dpi = 300)
```
```{r fig.id = "plot", fig.cap = "boxplot imported from images folder", fig.height = 6, fig.width = 7.5, echo = FALSE}
knitr::include_graphics("images/plot.png")
```
Does this helps somehow?
After implementing #David Gohel answer for a few projects. I still am envious of the use of out.height and out.width in PDF outputs.
In most of my projects I have resorted to going into File Explorer, right clicking on the figure in question and writing down the images dimensions to calculate its aspect ratio.
In a typical officedown project I will only call fig.width so that I can make sure the figure is maximized to the size of the page while maintaining its original aspect ratio.
knitr::include_graphics("images/plot.png")
I worked on trying to implement this automatically which would require reading the images dimensions to set fig.asp. Its not perfect, and I am sure someone else will have a much better and cleaner approach but you can accomplish this using the magick package. This also requires 2 chunks to accomplish the feat (again not optimal)
{r, eval=TRUE, echo=FALSE}
# First chunk to fetch the image size and calculate its aspect ratio
img <- magick::image_read("images/plot1.png") # read the image using the magic library
img.asp <- image_info(img)$height / image_info(img)$width # calculate the figures aspect ratio
{r fig.width=11, fig.asp = img.asp, fig.id="plot", fig.cap="boxplot imported from images folder", echo=FALSE}
# second chunk uses "img.asp" to make sure our aspect ratio is maintained.
knitr::include_graphics("images/plot.png")

I want text between figures but it shows text above figures

I am creating a pdf with bookdown.
My problem is that I have the text between figures but it shows the text above the figures and the figures below one by one.
index.Rmd
---
title: "A title"
author: "George"
date: "`r Sys.Date()`"
output:
bookdown::tufte_book2: default
description: V
documentclass: book
link-citations: yes
bibliography: book.bib
site: bookdown::bookdown_site
biblio-style: apalike
---
02-explore.Rmd
# Explore {#explore}
```{r global, echo=FALSE, include=FALSE}
library(knitr)
knitr::opts_chunk$set(cache = TRUE, warning = FALSE, message = FALSE, tidy = FALSE,
fig.width = 6, fig.height = 4, dev = "cairo_pdf")
# list libraries and load data frame
```
Text goes here .
```{r title1, echo = FALSE, fig.cap = "One"}
ggplot
```
Another text .
```{r stw-title2, echo = FALSE, fig.cap = "Two"}
ggplot
```
output.yml
bookdown::tufte_book2:
includes:
in_header: preamble.tex
before_body: dedication.tex
after_body: after.tex
latex_engine: xelatex
citation_package: natbib
So, I want some text , first figure below , another text and another figure below, but instead I am receiving all text above all figures.
I found that if I use :
fig.width = 5 and fig.aps = 1/2 (or 1/3)
then the text and figures appear in the right order.
So, it was a problem with fig.height.

Unable to produce landscape orientation microsoft word document from R markdown when using classoption: landscape

I am unable to produce a landscape orientation document when using RStudio and Rmarkdown.
R is version 3.4.2
RStudio is version 0.98.1103
I cannot change these as they are the latest versions on the cluster which I run my programs on.
After knitting the document, I do get a document out (in portrait form), however get the following error message:
Output created: test_landscape.docx
Warning message:
In (function (toc = FALSE, toc_depth = 3, fig_width = 5, fig_height = 4, :
table of contents for word_document requires pandoc >= 1.14
Reproducible code is here:
---
title: "test_landscape"
author: "Name"
date: "09/10/2018"
output: word_document
classoption: landscape
---
Test for landscape orientation
```{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.
Unsure if this is more suited to cross validated, as R is a statistical programming language, but the question is not a statistical one.
Thank you.
EDIT: Have edited title to better represent my problem after the below comment.
Thanks to Ralf Stubner.
There is a good explanation for the process of how to do this specifically for word here: https://rmarkdown.rstudio.com/articles_docx.html
You must create a word document that has the setting (e.g. landscape orientation) that you want, save it in the same location as your .Rmd file and then refer to it as the reference document, e.g.:
---
title: "test_landscape"
author: "Name"
date: "09/10/2018"
output:
word_document:
reference_docx: word_styles.docx
---

Download charts in flexdashboard

I am trying to use a download button in the input column of a flex dashboard to download a collection of charts rendered as *.pdf. The entire dashboard works just fine, and the download button renders properly; however, when I click the download button, the file that does get downloaded does not contain the intended charts. The warning I get from my Mac when it tries to open the file is that the file might be damaged or that it's a form that Preview (or Acrobat) doesn't recognize. The following is a highly redacted form of my code that contains the problematic sections. Any guidance on how to get charts to download in a flexdashboard as charts download in Shiny?
---
title: "My Model"
runtime: shiny
output:
flexdashboard::flex_dashboard:
theme: cerulean
vertical_layout: scroll
orientation: rows
---
```{r global, include=FALSE}
library(shiny)
library(shinyBS)
library(shinyWidgets)
library(flexdashboard)
library(tidyverse)
library(readxl)
library(knitr)
library(RColorBrewer)
source("MLHS_Distributions.R")
source("interp.R")
source("tooltips.R")
```
```{r Inputs}
downloadButton("downlaodReport","Price Comparision Report")
downloadHandler(filename = function() {
filename = paste0("ModelReport-", Sys.Date(), ".pdf")
},
content = function(file) {
pdf(file, width = 8.5, height = 6.14)
renderPrint({output$gg.prob.win.price()})
dev.off()
}
)
```
```{r priceProbWinChart}
renderPlot({
gg.prob.win.price <- --ggplot code--
plot(gg.prob.win.price)
})
```

Rmarkdown - how to remove grey background on output

I am experiencing a slightly irritating problem, which is that I am not able to remove the grey text from output (please see picture below).
I've searched for a solution, but is restricted by my lack of knowledge about the proper terms, and therefore I am not able to find any solutions.
I know this can be somehow bypassed by using only one "`", yet I need the triple "```" in order to run my code interpreting rows.
The grey background on output
---
title: "Untitled"
output: word_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r, echo=FALSE}
hej <- ("test")
print(hej)
```
You might simply want to override the grey highlighting in the YAML header as follows:
---
title: "Untitled"
output:
word_document:
highlight: NULL
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
Now if you want to get rid of the "##" and the line-numbers, tell knitr to handle texts as-is, and use cat():
```{r textfoo, echo = FALSE, results = 'asis'}
hej <- ("test")
cat(hej)
```
Et voilĂ :