Table title on a different page when using a flextable object in a officedown document - flextable

I'm trying to put together a document where a "Tables" section will be found at the end of it. There, all the tables that I will have cited throughout the document will be shown.
My problem is that whenever I have a long table spanning several pages, the table title is left alone on one page and the table follows on the next page. This occurs in both portrait and landscape mode.
My question is: What Can I do with that so that table titles are found just above their associated tables, on the same page?
Here is a snapshot of the problem:
In portrait mode, the table is ok when showing only the first few lines (using the r head() function, left), while the whole table is incorrect (two pages on the right).
The same applies in landscape mode.
And here is the reproducible example.
```
---
output: officedown::rdocx_document
---
```
```{r setup, echo=F, message=F, warning=F}
knitr::opts_chunk$set(echo = F,
collapse = T,
fig.align = "center",
fig.width = 6,
fig.height = 8,
fig.cap = T,
fig.pos = "!h",
message = F,
warning = F)
library(magrittr) # for using the %>%
library(dplyr)
library(officedown)
library(officer)
library(flextable)
# portrait section
portrait <- prop_section(type = "continuous")
# landscape section
landscape <- prop_section(page_size = page_size(orient = "landscape"), type = "continuous")
# Function for setting widths
FitFlextableToPage <- function(ft, pgwidth = 6){
ft_out <- ft %>% autofit()
ft_out <- width(ft_out, width = dim(ft_out)$widths*pgwidth /(flextable_dim(ft_out)$widths))
return(ft_out)
}
set.seed(12345) # for reproducibility when setting table1
```
```{r, echo = F}
# Creation of table1
years <- 1990:2022
table1 <- tibble(year = years,
dat1 = sample(rnorm(n = 1000, 0, 2), size = length(years), replace = T)) %>%
mutate(year = as.character(year),
dat2 = dat1 * 10,
dat3 = dat1 * 1000)
#table1
```
# portrait table
```{r}
foot <- "Preliminary data." # footnote
col_names <- c("Year", "Column 1", "Column 2", "Column 3") # table headers
# Setting the footnote
cor <- which(with(table1, year %in% 2021:2022))
# length(cor) # 2
# Headers
names(table1) <- col_names
```
```{r table1, tab.cap = "Header of table1 in portrait style."}
table1 %>% head() %>% flextable() %>% autofit()
```
\newpage
```{r table2, tab.cap = "All of table1 in portrait style + footnote."}
table1 %>%
flextable() %>%
footnote(i = cor, j = 1, value = as_paragraph(foot),
ref_symbols = "a", part = "body")
block_section(portrait) # end of portrait section
```
# landscape table
Let's put these same tables on a landscape page.
```{r table3, tab.cap = "Header of table1 in landscape style."}
table1 %>% head() %>% flextable() %>% autofit()
```
\newpage
```{r table4, tab.cap = "All of table1 in landscape style + footnote."}
table1 %>%
flextable() %>%
footnote(i = cor, j = 1, value = as_paragraph(foot),
ref_symbols = "a", part = "body") %>%
FitFlextableToPage(pgwidth = 9.5)
block_section(landscape) # end of landscape section
```
# New section in portrait style
bla bla bla.

As David Gohel kindly replied, the chunk option ft.keepnext was the key here and needed to be set to FALSE in the example. This was done by adding an extra argument in the opts_chunk$set() at the beginning of the script, such as:
knitr::opts_chunk$set(echo = F,
collapse = T,
fig.align = "center",
fig.width = 6,
fig.height = 8,
fig.cap = T,
fig.pos = "!h",
message = F,
warning = F,
ft.keepnext = F) # the argument added

Related

R: Modifying an R Markdown Tutorial

I am working with the R programming language.
I have the following 8 plots have been made beforehand and saved as HTML files in my working directory:
library(plotly)
Red_A <- data.frame(var1 = rnorm(100,100,100), var2 = rnorm(100,100,100)) %>%
plot_ly(x = ~var1, y = ~var2, marker = list(color = "red")) %>%
layout(title = 'Red A')
Red_B <- data.frame(var1 = rnorm(100,100,100), var2 = rnorm(100,100,100)) %>%
plot_ly(x = ~var1, y = ~var2, marker = list(color = "red")) %>%
layout(title = 'Red B')
Blue_A <- data.frame(var1 = rnorm(100,100,100), var2 = rnorm(100,100,100)) %>%
plot_ly(x = ~var1, y = ~var2, marker = list(color = "blue")) %>%
layout(title = 'Blue A')
Blue_B <- data.frame(var1 = rnorm(100,100,100), var2 = rnorm(100,100,100)) %>%
plot_ly(x = ~var1, y = ~var2, marker = list(color = "red")) %>%
layout(title = 'Blue B')
htmlwidgets::saveWidget(as_widget(Red_A), "Red_A.html")
htmlwidgets::saveWidget(as_widget(Red_B), "Red_B.html")
htmlwidgets::saveWidget(as_widget(Blue_A), "Blue_A.html")
htmlwidgets::saveWidget(as_widget(Blue_B), "Blue_B.html")
My Question: Using this template over here (https://testing-apps.shinyapps.io/flexdashboard-shiny-biclust/) - I would like to make a flexdashboard that allows the user to select (from two dropdown menus) a "color" and a "letter" - and then render one of the corresponding graphs (e.g. col = Red & letter = B -> "Red B"). I would then like to be able to save the final product itself as an HTML file. This would look something like this:
I tried to write the Rmarkdown Code for this problem by adapting the tutorial:
---
title: "Plotly Graph Selector"
output:
flexdashboard::flex_dashboard:
orientation: columns
vertical_layout: fill
runtime: shiny
---
Inputs {.sidebar}
selectInput("Letter", label = h3("Letter"),
choices = list("A" = 1, "B" = 2),
selected = 1)
selectInput("Color", label = h3("Color"),
choices = list("Red" = 1, "Blue" = 2),
selected = 1)
How can I continue with this?
Note
I know that it is possible to load HTML files into a dashboard that have been made beforehand, e.g.
# https://stackoverflow.com/questions/73467711/directly-loading-html-files-in-r
<object class="one" type="text/html" data="Red_A.html"></object>
<object class="one" type="text/html" data="Red_B.html"></object>
<object class="one" type="text/html" data="Blue_A.html"></object>
<object class="one" type="text/html" data="Blue_B.html"></object>
You could use iframe with renderUI to render the HTML files locally using addResourcePath with the location of your files. With paste0 and paste your could dynamically create the html files to select them. Here is some reproducible code:
---
title: "Plotly Graph Selector"
output:
flexdashboard::flex_dashboard:
orientation: columns
vertical_layout: fill
self_contained: false
runtime: shiny
---
```{r global, include=FALSE}
```
Inputs {.sidebar}
-----------------------------------------------------------------------
```{r}
selectInput("Letter", label = h3("Letter"),
choices = c("A", "B"),
selected = "A")
selectInput("Color", label = h3("Color"),
choices = c("Red", "Blue"),
selected = "Red")
```
Row
-----------------------------------------------------------------------
```{r}
addResourcePath("Downloads", "~/Downloads")
renderUI({
color <- input$Color
letter <- input$Letter
tags$iframe(
seamless="seamless",
src=paste0("Downloads/", paste0(paste(color, letter, sep = "_"), ".html")),
width = 600,
height = 400)
})
```
Output:
If you want to remove the border around the plot, you could add frameBorder = "0" in your iframe call like this:
```{r}
addResourcePath("Downloads", "~/Downloads")
renderUI({
color <- input$Color
letter <- input$Letter
tags$iframe(
seamless="seamless",
src=paste0("Downloads/", paste0(paste(color, letter, sep = "_"), ".html")),
width = 600,
height = 400,
frameBorder = "0")
})
```
Output:
Using getwd() with basename like this:
```{r}
addResourcePath(basename(getwd()), getwd())
renderUI({
color <- input$Color
letter <- input$Letter
tags$iframe(
seamless="seamless",
src=paste0(basename(getwd()), "/", paste0(paste(color, letter, sep = "_"), ".html")),
width = 600,
height = 400,
frameBorder = "0")
})
```

R markdown table loop NULL outcome

My code is producing a lot of NULLs at the end in the html output.
Could you please help me to prevent it?
---
title: "Test"
output: html_document
---
```{r warning=FALSE, message=FALSE, results = 'asis',echo=FALSE}
library(tidyverse)
library(knitr)
library(kableExtra)
# nest all data except the cut column and create html tables
diamonds_tab <- diamonds %>%
nest(-cut) %>%
mutate(tab = map2(cut,data,function(cut,data){
writeLines(landscape(kable_styling(kable(as.data.frame(head(data)),
caption =cut,
format = "html",align = "c",row.names = FALSE),
latex_options = c("striped"), full_width = T)))
}))
# print tab column, which contains the html tables
invisible(walk(diamonds_tab$tab, print))
```
Instead of using invisible, wrap the print command with capture.output.
---
title: "Test"
output: html_document
---
```{r warning=FALSE, message=FALSE, results = 'asis',echo=FALSE}
library(tidyverse)
library(knitr)
library(kableExtra)
# nest all data except the cut column and create html tables
diamonds_tab <- diamonds %>%
nest(-cut) %>%
mutate(tab = map2(cut,data,function(cut,data){
writeLines(landscape(kable_styling(kable(as.data.frame(head(data)),
caption =cut,
format = "html",align = "c",row.names = FALSE),
latex_options = c("striped"), full_width = T)))
}))
# print tab column, which contains the html tables
walk(diamonds_tab$tab, ~ capture.output(print(.x)))
```
I found out, that it is only enough to remove the walk.

Several lines with different style in Caption in both html and docx - flextable

I need to show data caption, computer name and period in the header of table.
I have also requirements: zebra theme, merging cells if needed. That's why I chose flextable.
Here is my code:
library(officer) # border settings library
library(flextable) # drawing tables library
library(dplyr)
Caption <- "<b><big>Computer01.domain.com</big></b><br>Network Interface<br>Gbit Total/sec<br><small>2021-05-14 18:04 to 2021-05-25 13:29</small>"
bold_border <- fp_border(color="gray", width =2)
std_border <- fp_border(color="gray")
stub <- "2021-05-14 01:40 to 2021-05-17 08:26"
table_data <- data.frame (
Instance = c("Intel[R] Ethernet 10G",
"Intel[R] Ethernet Converged Network Adapter _1",
"Intel[R] Ethernet Converged Network Adapter _2",
"Intel[R] Ethernet 10G",
"Intel[R] Gigabit"),
Max = c(2.45, 2.41, 2.29, 2.17, 0),
Avg = c(0.15, 0.15, 0.15, 0.17, 0)
)
table <- table_data %>% flextable() %>%
set_caption(caption = Caption , html_escape = F) %>%
bg(bg = "#579FAD", part = "header") %>%
color(color = "white", part = "header") %>%
theme_zebra(
odd_header = "#579FAD",
odd_body = "#E0EFF4",
even_header = "transparent",
even_body = "transparent"
) %>%
set_table_properties(width = 1, layout = "autofit") %>%
hline(part="all", border = std_border ) %>%
vline(part="all", border = std_border ) %>%
border_outer( border = bold_border, part = "all" ) %>%
fix_border_issues() %>%
set_header_labels(
values = list(Instance = InstanceName ) ) %>%
flextable::font (part = "all" , fontname = "Calibri")
save_as_docx( table, path = file.path("c:\\temp", "test01.docx") )
save_as_html (table, path = file.path("c:\\temp", "test01.html"))
Here is what I got in html which is okay for me:
But in docx format my header style is not applied:
How can I create header like I did for html that can be saved to both html and docx?
If I have to create separate tables - one for html, other for docx - it's not so good but acceptable options. That case my question how to create header I made in html but for docx format?

Remove a flextable columns after the flextable creation

I create a flextable based on a csv file, I put some style on it, change some cells. Then I would like to remove a specific columns of this flextable before add it to a doc.
Is-there a way to create a copy of a flextable and specifying col_keys?
mydf <- GetData(....)
cols <- names(mydf)
myft <- flextable(mydf, col_keys = cols)
# Adding style to ft...
# ....
# Here I want to remove one column to the ft (and only here, not when first creating the ft)
# something as:
# ft <- CreateCopyOfFlextable(ft,cols[-which(cols=='COLB')])
#
my_doc <- read_docx()
my_doc <- my_doc %>% body_add_par("") %>%
body_add_flextable(value = ft)
print(my_doc, target = 'c:/temp/doc.docx')
I just had the same problem and had a devil of a time Googling for a solution. #David-Gohel truly has the answer here, but I feel the need to provide a similar solution with additional explanation.
My problem and the OPs is that we wanted to use the data from columns that wouldn't be displayed to influence the formatting of columns that will be displayed. The concept that was not initially obvious is that you can send a data frame to flextable with more columns than you intend to display (instead of displaying all and deleting them you've used them). Then, by using the col_keys argument, you can select only those columns that you want to display while keeping the remaining ones around for additional processing (e.g., for using compose(), paragraph(), or add_chunk()).
If I understand correctly, COLB is supposed to be a flag to indicate that certain rows of COLC should be modified. If so, then my solution looks like this:
library(flextable)
library(magrittr)
library(officer)
df <- data.frame(COLA=c('a', 'b', 'c'),
COLB=c('', 'changevalue', ''),
COLC=c(10, 12, 13))
ft <- flextable(df, col_keys = c("COLA", "COLC")) %>% # Retain but don't display COLB
compose(i = ~ COLB =='changevalue', # Use COLB for conditional modifications
j = "COLC",
value = as_paragraph(as_chunk('100')),
part = 'body') %>%
style(i = ~ COLB =='changevalue', # Use COLB for conditional formatting on COLC
j = "COLC",
pr_t = fp_text(color = "black",
font.size = 11,
bold = TRUE,
italic = FALSE,
underline = FALSE,
font.family = "Times New Roman"),
part = "body")
ft
And here's what the above code produces (e.g., the "changevalue" column is the trigger for conditionally inserting 100 in COLC and also for changing the formatting):
library(flextable)
library(magrittr)
library(officer)
df <- data.frame(COLA=c('a','b','c'),
COLB=c('','changevalue',''),
COLC=c(10,12,13))
ft<-flextable(df, col_keys = c("COLA", "COLB"))
ft <- ft %>%
style(i= ~ COLB=='changevalue',
pr_t=fp_text(color="black", font.size=11, bold=TRUE, italic=FALSE, underline=FALSE, font.family="Times New Roman"),part="body")
ft<-compose(ft, i=2, j="COLB", value = as_paragraph(as_chunk('100')),part = 'body')
ft
I'm styling another column based on COLB.
Here an example:
df <- data.frame(COLA=c('a','b','c'),COLB=c('','changevalue',''),COLC=c(10,12,13))
ft<-flextable(df)
ft <- ft %>% style(i=which(ft$body$dataset$COLB=='changevalue'),pr_t=fp_text(color="black", font.size=11, bold=TRUE, italic=FALSE, underline=FALSE, font.family="Times New Roman"),part="body")
ft<-compose(ft, i=2,j=3, value = as_paragraph(as_chunk('100')),part = 'body')
# now I want to remove the COLB columns as I don't need it anymore
# ???????
my_doc <- read_docx()
my_doc <- my_doc %>% body_add_par("") %>% body_add_flextable(value = ft)
print(my_doc, target = 'c:/temp/orliange_p/sample.docx') %>% invisible()

Why is the layout of a graph from visnetwork in html too small

When I render the example-Rmd below, it looks like this (with Chrome, not really a difference to Firefox):
The figure is way too small and if I look at the "real" graphs I need, the height is too small and the ratio height-width is even worse.
Here is a reproducible example:
---
title: "Untitled"
author: "author"
date: "9 Mai 2018"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Example
Here is a line of text...................................................................................................................................................................................................................................................................
```{r echo=FALSE}
require(visNetwork, quietly = TRUE)
# minimal example
nodes <- data.frame(id = 1:20)
edges <- data.frame(from = sample(c(1:20), 10), to = sample(c(1:20), 10))
visNetwork(nodes, edges, width = "100%", height = "100%") %>%
visNodes() %>%
visOptions(highlightNearest = TRUE) %>%
visInteraction(navigationButtons = TRUE,
dragNodes = FALSE,
dragView = FALSE, zoomView = FALSE) %>%
visEdges(arrows = 'to')
```
Here is another line of text....................................................................................................................................................................................................................................................................
I expected to fix it using some chunk options, such as out.height or fig.height but for some reason they don't.
However you can set a fixed height for the widget itself, simply passing a number to the height argument that will be interpreted as pixels:
```{r echo=FALSE}
require(visNetwork, quietly = TRUE)
# minimal example
nodes <- data.frame(id = 1:20)
edges <- data.frame(from = sample(c(1:20), 10), to = sample(c(1:20), 10))
visNetwork(nodes, edges, width = "100%", height = 700) %>%
visNodes() %>%
visOptions(highlightNearest = TRUE) %>%
visInteraction(navigationButtons = TRUE,
dragNodes = FALSE,
dragView = FALSE, zoomView = FALSE) %>%
visEdges(arrows = 'to')
```