Rmarkdown officer / officedown / flextables problem - r-markdown

I have the following rmd script. I've spent a few days trying to get this to work but I am failing miserably. Basically I need help with three things. I am happy to post three separate questions if needed.
The multicolumn options/code are completely ignored. The corporatetable.docx is in landscape and has a typical corporate style. I need to have a full width landscape -> two column landscape -> full width landscape. If I could get the two column landscape setup to work, the remaining style would be inherited by corporatetable.docx. If I could get help with only one - I would need this.
When I run the rmd it generates a word file but none of the corporate styles are in there. It just uses my word's default colors etc. The difference is very clear - no landscape, single column and blue instead of red. How do I correctly pass the officedown::rdocx_document: to reference my word file because it's clearly not picking it up and no warning or error is generated?
If you see in the second chunk I am using flextable to show two pictures (which are passed through params) in the word report and align them with some information. myft works but it prints the (temporary/volatile) path instead of showing the pictures in the report. For reference if I use knitr::include_graphics(c(params$x1,params$x2)) it works fine.
I'm really stuck on these. Any help is welcome.
---
title: "Title"
subtitle:
params:
x1: x1
x1_name: x1_name
x1_email : x1_email
x2: x2
x2_name: x2_name
x2_email : x2_name
output:
officedown::rdocx_document:
reference_docx: corporatetemplate.docx
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(officedown)
library(officer)
library(flextable)
knitr::opts_chunk$set(out.width = '100%', dpi=300)
```
<!---BLOCK_MULTICOL_START--->
This text is on column 1. Please work
```{r somecodechunk, echo=FALSE, out.width="75px", include=TRUE, strip.white=TRUE}
library(flextable)
# this works but prefer to use flextable
# if(all(!is.null(params))) {
# knitr::include_graphics(c(params$x1,params$x2))} else {
# }
myft <- data.frame(
"pic1" = rep("",3),
"details1" = c(params$x1_name,"+X XXX XXX X",params$x1_email),
"pic2" = rep("",3),
"details2" = c(params$x2_name,"+X XXX XXX X",params$x2_email)
)
myft <- flextable(myft)
myft <- merge_at(myft, i = 1:3, j = 1 )
myft <- merge_at(myft, i = 1:3, j = 3 )
myft <- compose(myft,i = 1, j = 1, value = as_paragraph(as_image(params$x1), part = "body"))
myft <- compose(myft,i = 1, j = 3, value = as_paragraph(as_image(params$x2), part = "body"))
autofit(myft)
#Ok this does not work because the pics are not shown
```
`r run_columnbreak()`
This text is on column 2. Please work
This text is on column 2. Please work
`r run_linebreak()`
<!---BLOCK_MULTICOL_STOP{widths: [4,4], space: 0.2, sep: true}--->
\pagebreak
Back to full width with some text
\pagebreak

Related

Printing formatted markdown text with Officedown knit_print_block

I'm using the officedown function knit_print_block to print figure captions in Rmarkdown, with MS Word output. This is needed because I'm looping through lots of figures, and need each to return the captioned figure, as well as a cross-reference.
All's well with plain text. I can get the caption printed, and have a cross-reference object as well. However, if I try to use basic markdown formatting (in this case to superscript a value), such as t/nmi^2^, this does not return a superscript in the Word document. I have tried to return XML text as well (as documentation onknit_print_block states 'the function only print XML code') but do not return a superscripted value. Below is a minimal .Rmd example. It simply uses the mtcars dataset to make a meaningless plot, and then tries to return captions and bookmarks.
---
output: officedown::rdocx_document
---
```{r setup, include=FALSE}
library(officedown)
library(officer)
library(ggplot2)
```
```{r, echo = FALSE, message=FALSE, warning=FALSE, fig.width= 7, fig.height= 4, results = 'asis'}
for (i in 1:2){
#make a placeholder plot
tmp_plot = ggplot(mtcars, aes(x = mpg , y = hp )) +
geom_point()
print(tmp_plot)
#build the caption
cap_text = paste0('Density (t/nmi^2^) in sample ', i)
#build the bookmark
fig_name = paste0('samplesummary', i)
#build the caption
tmp_fig_caption = block_caption(cap_text,
style = 'Normal',
autonum = run_autonum(seq_id = 'fig',
pre_label = "Figure ",
bkm = fig_name))
#print caption
officedown::knit_print_block(tmp_fig_caption)
}
```
Just some normal text. Are cross-refernces returned? Yep: Figure\#ref(fig:samplesummary1), Figure \#ref(fig:samplesummary2)

Rmarkdown plot and image side by side

I'm working on a report in R markdown.
I know there is a way to have different plots side by side, and there is also a way to have different images side by side.
But is it also possible to show a plot and an image side by side?
I have a ggplot bar graph that I would like to present next to an image of a map, it takes up too much space if I put the image below the graph.
Thanks,
Regards,
Freya
This could work to you. Here is the step by step, with an indication of the code between parentheses.
First, you need to load the image (y), by creating an object (photo).
Second, you create a ggplot with the image (photo_panel).
Finally, after creating your plot (p1), you use the library cowplot to plot a grid (plot_grid).
.Rmd file:
---
title: "Image + graph"
author: bttomio
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
## R Markdown
```{r image_graph}
y = "http://upload.wikimedia.org/wikipedia/commons/5/5d/AaronEckhart10TIFF.jpg"
download.file(y,'y.jpg', mode = 'wb')
library("jpeg")
photo <- readJPEG("y.jpg",native=TRUE)
library(ggplot2)
library(cowplot)
photo_panel <- ggdraw() + draw_image(photo, scale = 0.8)
df <- data.frame(Years=rep(2016:2017, each=4),
Quarters=rep(paste0("Q", 1:4), 2),
Series1=seq(100, 800, 100))
library(ggplot2)
p1 <- ggplot(df) +
geom_point(aes(x=Quarters, y=Series1)) +
facet_wrap( ~ Years, strip.position="bottom", scales="free_x") +
theme(panel.spacing=unit(0, "lines"),
strip.background=element_blank(),
strip.placement="outside",
aspect.ratio=1) # set aspect ratio
plot_grid(p1, photo_panel, ncol = 2)
```
Output:

Restart Figure Numbering for Appendix / Supplementary Material in bookdown

I am writing an article for a journal that requires Supplementary Material. I was hoping to use a unique label such as SuppMat: instead of the default fig: to send Figures and Tables into this section. If not, I can use the default fig label but I need numbering to restart in the Supplementary Material section of the document.
I am aware of one answer using latex (found here) but I must complete this when exporting to docx. Below is a reproducible example using officedown
---
output:
officedown::rdocx_document
---
```{r setup, include=FALSE}
pacman::p_load(knitr, officedown, officer)
knitr::opts_chunk$set(echo = FALSE,
eval = TRUE,
fig.cap = TRUE)
```
# Main Text
Please see Supplementary Figure \#ref(fig:appendix-fig1) and Figure \#ref(fig:main-fig1).
```{r fig.id="main-fig1", fig.cap="This should be labelled **Figure 1**"}
barplot(1:5, col=1:5)
```
```{r tab.id="main-tab1", tab.cap="Main Text Table 1"}
head(mtcars)
```
\newpage
# Supplementary Materials {#SuppMat}
```{r fig.id="appendix-fig1", fig.cap="This figure should be labelled **Supplementary Figure 1**"}
barplot(1:5, col=1:5)
```
```{r tab.id="appendix-tab1", tab.cap="Should be labelled **Supplementary Table 1**"}
head(mtcars)
```
After searching multiple forums and hours, I was able to come up with a solution using the officedown package. Hopefully this helps someone else out. For further details check out the run_autonum function.
---
output: officedown::rdocx_document
---
```{r setup, include=FALSE}
pacman::p_load(officedown, officer, knitr)
knitr::opts_chunk$set(echo = FALSE, fig.cap = TRUE)
ft_base <- fp_text(font.family = "Cambria", font.size = 12, bold = TRUE)
ft1 <- update(ft_base, shading.color='#EFEFEF', color = "red")
ft2 <- update(ft_base, color = "#C32900")
srcfile <- file.path( R.home("doc"), "html", "logo.jpg" )
extimg <- external_img(src = srcfile, height = 1.06/5, width = 1.39/5)
```
## References
This is a reference to an supplementary image caption whose number is Supplementary Figure \#ref(fig:faithfuld-plot) and \#ref(fig:supp-bar).
Testing another figure with a barplot in Figure \#ref(fig:plotbar)
```{r fig.id="plotbar", fig.cap = "Main Figure"}
barplot(1:8, col=1:2)
```
## Supplementary Material
```{r fig.id="faithfuld-plot"}
knitr::include_graphics("images/MyImage.png") # Use your own figure here (I needed to test with knitr for my workflow)
block_caption("First Appendix Figure",
style = "Figure",
autonum = run_autonum(seq_id = 'fig',
bkm = 'faithfuld-plot',
pre_label = "Supplemental Figure ",
start_at=1))
```
```{r fig.id="supp-bar"}
barplot(1:8, col=1:2)
block_caption("Second Appendix Figure",
style = "Figure",
autonum = run_autonum(seq_id = 'fig',
bkm = 'supp-bar',
pre_label = "Supplemental Figure ",
start_at= NULL))
```

Pre-populate data tables and charts using shiny_prerendered in Rmd flexdashboard

I have a shiny app created with Rmd / Flexdashboard with many charts and tables. It is working well. Recently, I started using shiny_prerendered to improve the UX during startup. Now the page loads up faster but all the sections are empty (this is expected - the html renders but the charts and tables are still waiting for data) until the server code runs.
Is it possible to have some placeholder data during setup that will load the shiny output? Reactive outputs are not recognized in the setup context. Is this what the server-start context is for? I have tried too that without success?
Here is a simple code with a two value boxes
---
title: "ValueBoxTest"
output:
flexdashboard::flex_dashboard:
vertical_layout: fill
theme: united
runtime: shiny
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, options(scipen = 1, digits = 2))
### load packages
```
# ValueBox Test
===============================================
## Row 1
### Box 1
```{r, context="server"}
output$value1 <- renderValueBox({
### p <- 100 starting value placeholder
### call function to generate "p"
p <- functionToGenerateValue()
valueBox(p, icon = "fa-usd")
})
```
```{r echo = FALSE}
valueBoxOutput("value1")
```
## Row 2
### Box 2
```{r, context="server"}
output$value2 <- renderValueBox({
### q <- 0 starting value placeholder
### call function to generate "q"
q <- functionToGenerateValue()
valueBox(q, icon = "fa-usd")
})
```
```{r echo = FALSE}
valueBoxOutput("value2")
Well, it may be simpler than you might think. For example, why don't you try to change from runtime:shiny to runtime:shiny_prerendered? It may do the trick.

Is there a way to have previous/next links at the bottom of shiny presentations?

I am working in RStudio and creating a markdown Shiny presentation (which I believe uses IOslides).
Currently the generated presentation doesn't have any navigational help, the user has to know they need to use left/right arrows to move to the next or previous slides. Even when deployed to server I don't see any arrows at the bottom of presentations.
I have searched through documentation and here to see if this is possible, but can't seem to find anything.
Is there some setting to include a Previous/Next type link at the bottom of every slide?
Process to create my presentation in R Studio:
New file > R Markdown > Shiny > Shiny presentation
The issue occurs even with the sample code when creating a new file - there are no navigation arrows
Published example (where there are no navigation arrows):
https://regolith.shinyapps.io/test
And the sample code (as generated by R studio):
---
title: "test"
author: ""
date: "24 January 2017"
output: ioslides_presentation
runtime: shiny
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
## Shiny Presentation
This R Markdown presentation is made interactive using Shiny. The viewers of the presentation can change the assumptions underlying what's presented and see the results immediately.
To learn more, see [Interactive Documents](http://rmarkdown.rstudio.com/authoring_shiny.html).
## Interactive Plot
```{r eruptions}
inputPanel(
selectInput("n_breaks", label = "Number of bins:",
choices = c(10, 20, 35, 50), selected = 20),
sliderInput("bw_adjust", label = "Bandwidth adjustment:",
min = 0.2, max = 2, value = 1, step = 0.2)
)
renderPlot({
hist(faithful$eruptions, probability = TRUE, breaks = as.numeric(input$n_breaks),
xlab = "Duration (minutes)", main = "Geyser eruption duration")
dens <- density(faithful$eruptions, adjust = input$bw_adjust)
lines(dens, col = "blue")
})
```
## Bullets
- Bullet 1
- Bullet 2
- Bullet 3
## R Output
```{r cars}
summary(cars)
```