Reduce row height / margins in Datatable? - html

I'm using a datatable in a shiny app with custom coloring of the cells. This is done in html (each cell is a div) and by telling DT to not escape these specific columns.
It looks like this with DT :
screenshot
My issue is that I would like the coloring to take the entire height of each cell so that there is no margins. If I could have the different cell colors to touch each other that would be great.
I have try to add margin: 0px; padding: 0px; but it makes no difference.
I've also tried to use the formatstyle from DT to reduce the row height like so :
formatStyle( 0, target = 'row', lineHeight = '80%')
and the result looks like this :
screenshot 2
I'm currently trying with padding: 0px;margin-top:0px;margin-right:0px;margin-bottom:0px;margin-left:0px; but it does not work any better.
It looks to me that this is a margin from DT rather than my div since whatever I try in my div style, I've always the same margins between the colors and the row height limits. The only thing is I do not know how to control it.
Would anyone know how to achieve such a result ?
Thanks ahead of time for your help.
Code used :
for (c in colnames(ranking)[10:13]) {
ranking <- ranking %>%
filter(param %in% input$param) %>%
arrange_(.dots = c) %>%
mutate(!!paste0(c, "_rk") := 1:nrow(ranking %>% filter(param %in% input$param)))
tmp <- ranking %>%
arrange_(.dots = c) %>%
select_(.dots = c)
max <- tmp %>% tidyr::drop_na() %>% .[, 1] %>% max()
min <- tmp %>% tidyr::drop_na() %>% .[, 1] %>% min()
range <- max - min
brks <- vector(length = colors)
for (i in 1:colors) {
brks[i] <- i^pracma::bisect(function(x) range^(1/x) - (colors + 1), 1, 5)$root %>% round(2) + min - 2
}
tmp <- tmp %>%
mutate(brks = ifelse(is.na(tmp[, 1]),
NA,
cut(tmp %>% tidyr::drop_na() %>% .[, 1], brks)))
colfunc <- colorRampPalette(c("#c31432", "#ffc500", "#edde5d", "white"))
clrs <- colfunc(colors + 1)
tmp_nrow <- tmp %>% nrow()
for (i in 1:tmp_nrow) {
row <- which(tmp[i, 1] == ranking[,c])
r <- clrs[tmp[i, 2]] %>% col2rgb() %>% .[1]
g <- clrs[tmp[i, 2]] %>% col2rgb() %>% .[2]
b <- clrs[tmp[i, 2]] %>% col2rgb() %>% .[3]
tmp[i, 1] <- paste0("<center><div style='background: ", "radial-gradient(rgba(", r, ",", g, ",", b, ",", "0), rgba(", r, ",", g, ",", b, ",", "0.25), rgba(", r, ",", g, ",", b, ",", "1)", ")", "; border: solid 0px;font-family: \"Interstate Black\";font-weight: bolder;padding: 0;margin: 0;'>",
tmp[i, 1],
"</div></center>")
ranking[row,paste0(c, "_coloring")] <- tmp[i, 1]
}
}
ranking_m <- as.matrix(ranking %>%
filter(param %in% input$param) %>%
select(4, 47, 40, 38, 31, 32, 41, 42, 43, 44))
DT::datatable(ranking_m,
escape = c(TRUE, FALSE, rep(FALSE, 8)),
filter = 'top',
extensions = list('Responsive' = NULL),
options = list(pageLength = 25,
lengthMenu = c(10, 25, 50, 100),
columnDefs = list(list(width = '400px', targets = 0),
list(width = '25px', targets = 1),
list(className = 'dt-center', targets = 2:9)))) #%>%
# formatStyle( 0, target = 'row', lineHeight = '80%')

The background CSS must be set to the cells, not to the cells contents. This can be achieved with formatStyle. Here is an example with random colors:
library(DT)
dat <- iris[1:5,]
ncols <- ncol(dat)
# background for column 1
r <- sample.int(256, 5, replace = TRUE) - 1L
g <- sample.int(256, 5, replace = TRUE) - 1L
b <- sample.int(256, 5, replace = TRUE) - 1L
dat$RGB1 <- sprintf("radial-gradient(rgba(%s,%s,%s,0),rgba(%s,%s,%s,0.25),rgba(%s,%s,%s,1))",
r, g, b, r, g, b, r, g, b)
# background for column 2
r <- sample.int(256, 5, replace = TRUE) - 1L
g <- sample.int(256, 5, replace = TRUE) - 1L
b <- sample.int(256, 5, replace = TRUE) - 1L
dat$RGB2 <- sprintf("radial-gradient(rgba(%s,%s,%s,0),rgba(%s,%s,%s,0.25),rgba(%s,%s,%s,1))",
r, g, b, r, g, b, r, g, b)
# background for column 4
r <- sample.int(256, 5, replace = TRUE) - 1L
g <- sample.int(256, 5, replace = TRUE) - 1L
b <- sample.int(256, 5, replace = TRUE) - 1L
dat$RGB4 <- sprintf("radial-gradient(rgba(%s,%s,%s,0),rgba(%s,%s,%s,0.25),rgba(%s,%s,%s,1))",
r, g, b, r, g, b, r, g, b)
datatable(dat,
options =
list(
columnDefs =
list(
list(visible = FALSE, targets = ncols + 1:3),
list(className = "dt-center", targets = 1:ncols)
)
)) %>%
formatStyle(1, valueColumns = ncols+1, background = JS("value")) %>%
formatStyle(2, valueColumns = ncols+2, background = JS("value")) %>%
formatStyle(4, valueColumns = ncols+3, background = JS("value")) %>%
formatStyle(1:ncols, `font-family` = "Interstate Black") %>%
formatStyle(1:ncols, fontWeight = "bolder")

Related

How to merge 2 row headers in a single column in a data table and insert a reactive object?

This is the next step in my attempt to build a user-friendly transition matrix in R, a follow-on to post How to add a vertical line to the first column header in a data table?. I have been spoiled by the ease of drafting eye-friendly tables in Excel and have been struggling with this in R Shiny.
Running the MWE code at the bottom generates the transition table shown on the left side of the image below (with my comments overlaying). Expressing my question in Excel-speak, I'm trying to merge the top 2 cells (rows) in the left-most column (call them cells A1 and A2), eliminate the small bit of line just above "to_state" (cell A2)(item #1 in the image), eliminate that first column's header "to_state" (in cell A2)(item #2 in the image), and into that merged column header space insert an object similar to the object hovering over the "From" columns to the right, that states "To state where end period = x", where x is the value of object transTo() (item #3 in the image). Any suggestions for doing this? Using DT for the table rendering if possible.
I'm open to any other suggestion for drafting a user-friendly, understandable state transition matrix that delineates to/from columns/rows and reactively shows the to/from periods.
Post Shiny: Merge cells in DT::datatable seems promising but it addresses merging rows in the body of the table and not header rows.
Please note that in the fuller code, the table dynamically contracts/expands based on the number of unique states detected in the underlying data. States can range from 2 to 12.
MWE code:
library(DT)
library(shiny)
library(dplyr)
library(htmltools)
library(data.table)
data <-
data.frame(
ID = c(1,1,1,2,2,2,3,3,3),
Period = c(1, 2, 3, 1, 2, 3, 1, 2, 3),
Values = c(5, 10, 15, 0, 2, 4, 3, 6, 9),
State = c("X0","X1","X2","X0","X2","X0", "X2","X1","X0")
)
numTransit <- function(x, from=1, to=3){
setDT(x)
unique_state <- unique(x$State)
all_states <- setDT(expand.grid(list(from_state = unique_state, to_state = unique_state)))
dcast(x[, .(from_state = State[from],
to_state = State[to]),
by = ID]
[,.N, c("from_state", "to_state")]
[all_states,on = c("from_state", "to_state")],
to_state ~ from_state, value.var = "N"
)
}
ui <- fluidPage(
tags$head(tags$style(".datatables .display {margin-left: 0;}")), # < left-align the table
h4(strong("Base data frame:")),
tableOutput("data"),
h4(strong("Transition table inputs:")),
numericInput("transFrom", "From period:", 1, min = 1, max = 3),
numericInput("transTo", "To period:", 2, min = 1, max = 3),
h4(strong("Output transition table:")),
DTOutput("resultsDT"),
)
server <- function(input, output, session) {
results <-
reactive({
results <- numTransit(data, input$transFrom, input$transTo) %>%
replace(is.na(.), 0) %>%
bind_rows(summarise_all(., ~(if(is.numeric(.)) sum(.) else "Sum")))
results <- cbind(results, Sum = rowSums(results[,-1]))
})
output$data <- renderTable(data)
output$resultsDT <- renderDT(server=FALSE, {
req(results())
datatable(
data = results(),
rownames = FALSE,
filter = 'none',
container = tags$table(
class = 'display',
tags$thead(
tags$tr(
tags$th(colspan = 1, '', style = "border-right: solid 1px;"),
tags$th(colspan = 10, sprintf('From state where initial period = %s', input$transFrom))
),
tags$tr(
mapply(tags$th, colnames(results()), style = sprintf("border-right: solid %spx;", c(1L, rep(0, ncol(results())-1L))), SIMPLIFY = FALSE)
)
)
),
options = list(scrollX = F
, dom = 'ft'
, lengthChange = T
, pagingType = "numbers" # hides Next and Previous buttons
, autoWidth = T
, info = FALSE # hide the "Showing 1 of 2..." at bottom of table
, searching = FALSE # removes search box
),
class = "display"
) %>%
formatStyle(c(1), `border-right` = "solid 1px")
})
}
shinyApp(ui, server)
Please reference these related posts that lead to the solution shown at the bottom. The posts that built up to this solution are How to merge to row cells in data table?, How to add a vertical line to the first column header in a data table?, and How to add reactive object to secondary column header in output table?
Solution:
library(DT)
library(shiny)
library(dplyr)
library(htmltools)
library(data.table)
data <-
data.frame(
ID = c(1,1,1,2,2,2,3,3,3),
Period = c(1, 2, 3, 1, 2, 3, 1, 2, 3),
Values = c(5, 10, 15, 0, 2, 4, 3, 6, 9),
State = c("X0","X1","X2","X0","X2","X0", "X2","X1","X0")
)
numTransit <- function(x, from=1, to=3){
setDT(x)
unique_state <- unique(x$State)
all_states <- setDT(expand.grid(list(from_state = unique_state, to_state = unique_state)))
dcast(x[, .(from_state = State[from],
to_state = State[to]),
by = ID]
[,.N, c("from_state", "to_state")]
[all_states,on = c("from_state", "to_state")],
to_state ~ from_state, value.var = "N"
)
}
ui <- fluidPage(
tags$head(tags$style(".datatables .display {margin-left: 0;}")), # < left-align the table
h4(strong("Base data frame:")),
tableOutput("data"),
h4(strong("Transition table inputs:")),
numericInput("transFrom", "From period:", 1, min = 1, max = 3),
numericInput("transTo", "To period:", 2, min = 1, max = 3),
h4(strong("Output transition table:")),
DTOutput("resultsDT"),
)
server <- function(input, output, session) {
results <-
reactive({
results <- numTransit(data, input$transFrom, input$transTo) %>%
replace(is.na(.), 0) %>%
bind_rows(summarise_all(., ~(if(is.numeric(.)) sum(.) else "Sum")))
results <- cbind(results, Sum = rowSums(results[,-1]))
})
output$data <- renderTable(data)
output$resultsDT <- renderDT(server=FALSE, {
req(results())
datatable(
data = results(),
rownames = FALSE,
filter = 'none',
container = tags$table(
class = 'display',
tags$thead(
tags$tr(
tags$th(rowspan = 2, sprintf('To state where end period = %s', input$transTo), style = "border-right: solid 1px;"),
tags$th(colspan = 10, sprintf('From state where initial period = %s', input$transFrom))
),
tags$tr(
mapply(tags$th, colnames(results())[-1], style = sprintf("border-right: solid %spx;", rep(0, ncol(results()) - 1L)), SIMPLIFY = FALSE)
)
)
),
options = list(scrollX = F
, dom = 'ft'
, lengthChange = T
, pagingType = "numbers" # hides Next and Previous buttons
, autoWidth = T
, info = FALSE # hide the "Showing 1 of 2..." at bottom of table
, searching = FALSE # removes search box
),
class = "display"
) %>%
formatStyle(c(1), `border-right` = "solid 1px")
})
}
shinyApp(ui, server)

How to add a vertical line to the first column header in a data table?

I would like to add a vertical line to a DT table column header. There is guidance for adding this line in post How can I add a vertical line to a datatable?, but it applies to a static table where columns are manually set whereas in my MWE code (at bottom), the columns are set using the lapply() function in a reactive setting. So I'm having trouble using this guidance in my particular circumstances.
Any suggestions for adding a vertical line to the right of the left-most column header labeled "to_state"? As shown in this image which shows a portion of the output window when running the MWE code:
Please note that in the fuller code this MWE derives from, the table expands/contracts dynamically depending on the number of unique states detected in the underlying data. Therefore I can't use a static table set up like in the referenced related post above.
Once this is resolved, I'll have several additional questions as I struggle to make a transition table readily understandable for users (such as change the "to_state" left-most column header to "To end Period = [xxx]", but that will be addressed in another post). I'm tackling this formatting issue incrementally in baby steps.
I am very unfamiliar with HTML, CSS.
Here is the MWE code:
library(DT)
library(shiny)
library(htmltools)
library(data.table)
data <-
data.frame(
ID = c(1,1,1,2,2,2,3,3,3),
Period = c(1, 2, 3, 1, 2, 3, 1, 2, 3),
Values = c(5, 10, 15, 0, 2, 4, 3, 6, 9),
State = c("X0","X1","X2","X0","X2","X0", "X2","X1","X0")
)
numTransit <- function(x, from=1, to=3){
setDT(x)
unique_state <- unique(x$State)
all_states <- setDT(expand.grid(list(from_state = unique_state, to_state = unique_state)))
dcast(x[, .(from_state = State[from],
to_state = State[to]),
by = ID]
[,.N, c("from_state", "to_state")]
[all_states,on = c("from_state", "to_state")],
to_state ~ from_state, value.var = "N"
)
}
ui <- fluidPage(
tags$head(tags$style(".datatables .display {margin-left: 0;}")), # < left-align the table
h4(strong("Base data frame:")),
tableOutput("data"),
h4(strong("Transition table inputs:")),
numericInput("transFrom", "From Period:", 1, min = 1, max = 3),
numericInput("transTo", "To Period:", 2, min = 1, max = 3),
h4(strong("Output transition table:")),
DTOutput("resultsDT"),
)
server <- function(input, output, session) {
results <-
reactive({
results <- numTransit(data, input$transFrom, input$transTo) %>%
replace(is.na(.), 0) %>%
bind_rows(summarise_all(., ~(if(is.numeric(.)) sum(.) else "Sum")))
results <- cbind(results, Sum = rowSums(results[,-1]))
})
output$data <- renderTable(data)
output$resultsDT <- renderDT(server=FALSE, {
req(results())
datatable(
data = results(),
rownames = FALSE,
filter = 'none',
container = tags$table(
class = 'display',
tags$thead(
tags$tr(
tags$th(colspan = 1, '', style = "border-right: solid 1px;"),
tags$th(colspan = 10, sprintf('From initial Period = %s', input$transFrom))
),
tags$tr(
lapply(colnames(results()),
tags$th
)
),
)
),
options = list(scrollX = F
, dom = 'ft'
, lengthChange = T
, pagingType = "numbers" # hides Next and Previous buttons
, autoWidth = T
, info = FALSE # hide the "Showing 1 of 2..." at bottom of table
, searching = FALSE # removes search box
),
class = "display"
) %>%
formatStyle(c(1), `border-right` = "solid 1px")
})
}
shinyApp(ui, server)
We can use mapply instead of lapply to control the style parameter:
library(DT)
library(shiny)
library(dplyr)
library(htmltools)
library(data.table)
data <-
data.frame(
ID = c(1,1,1,2,2,2,3,3,3),
Period = c(1, 2, 3, 1, 2, 3, 1, 2, 3),
Values = c(5, 10, 15, 0, 2, 4, 3, 6, 9),
State = c("X0","X1","X2","X0","X2","X0", "X2","X1","X0")
)
numTransit <- function(x, from=1, to=3){
setDT(x)
unique_state <- unique(x$State)
all_states <- setDT(expand.grid(list(from_state = unique_state, to_state = unique_state)))
dcast(x[, .(from_state = State[from],
to_state = State[to]),
by = ID]
[,.N, c("from_state", "to_state")]
[all_states,on = c("from_state", "to_state")],
to_state ~ from_state, value.var = "N"
)
}
ui <- fluidPage(
tags$head(tags$style(".datatables .display {margin-left: 0;}")), # < left-align the table
h4(strong("Base data frame:")),
tableOutput("data"),
h4(strong("Transition table inputs:")),
numericInput("transFrom", "From Period:", 1, min = 1, max = 3),
numericInput("transTo", "To Period:", 2, min = 1, max = 3),
h4(strong("Output transition table:")),
DTOutput("resultsDT"),
)
server <- function(input, output, session) {
results <-
reactive({
results <- numTransit(data, input$transFrom, input$transTo) %>%
replace(is.na(.), 0) %>%
bind_rows(summarise_all(., ~(if(is.numeric(.)) sum(.) else "Sum")))
results <- cbind(results, Sum = rowSums(results[,-1]))
})
output$data <- renderTable(data)
output$resultsDT <- renderDT(server=FALSE, {
req(results())
datatable(
data = results(),
rownames = FALSE,
filter = 'none',
container = tags$table(
class = 'display',
tags$thead(
tags$tr(
tags$th(colspan = 1, '', style = "border-right: solid 1px;"),
tags$th(colspan = 10, sprintf('From initial Period = %s', input$transFrom))
),
tags$tr(
mapply(tags$th, colnames(results()), style = sprintf("border-right: solid %spx;", c(1L, rep(0, ncol(results())-1L))), SIMPLIFY = FALSE)
)
)
),
options = list(scrollX = F
, dom = 'ft'
, lengthChange = T
, pagingType = "numbers" # hides Next and Previous buttons
, autoWidth = T
, info = FALSE # hide the "Showing 1 of 2..." at bottom of table
, searching = FALSE # removes search box
),
class = "display"
) %>%
formatStyle(c(1), `border-right` = "solid 1px")
})
}
shinyApp(ui, server)

Plot and table in one figure in R markdown for HTML output

I'm working in Rbookdown and I want to place a plot and a table in one figure, how can I achieve that? Below is the code i used so far. Can you help?
```{r echo=FALSE, message=FALSE, warning=FALSE, fig.height = 3.5, out.width = '70%', fig.align = "center"}
library(knitr)
library(kableExtra)
library(tidyverse)
library(latex2exp)
options(scipen=999)
mu = 0
sigma = 1
x = 1
# draw normal distribution
range = seq(mu - 4*sigma, mu + 4*sigma, 0.01)
y = dnorm(range, mu, sigma)
plot(range, y,
main = "Standard Normal Distribution", xlab = "Z-score", ylab = " ",
type = 'l', ylim = c(0, max(y) + 0.01), axes = FALSE)
axis(1, at = seq(mu - 4*sigma, mu + 4*sigma, sigma))
# Add area to the left of x
cord.a = c(0, seq(min(range), x, 0.01))
cord.b = c(dnorm(seq(min(range), x, 0.01), mu, sigma), 0)
polygon(cord.a, cord.b, col = "#61a5ff")
text(x = 1.1, y = -.06, TeX('$z = 1.00$'), cex = .8, xpd=NA)
text(x = 0, y = .15, TeX('$p = .8413$'), cex = .8, xpd=NA)
# Create standard normal table
options(digits = 4)
u=seq(0,3.09,by=0.01)
p=pnorm(u)
m=matrix(p,ncol=10,byrow=TRUE)
df.m = as.data.frame(m)
z.values = c("**0.0**", "**0.1**", "**0.2**", "**0.3**", "**0.4**", "**0.5**", "**0.6**",
"**0.7**", "**0.8**", "**0.9**", "**1.0**", "**1.1**", "**1.2**", "**1.3**",
"**1.4**", "**1.5**", "**1.6**", "**1.7**", "**1.8**", "**1.9**","**2.0**",
"**2.1**", "**2.2**", "**2.3**", "**2.4**", "**2.5**", "**2.6**", "**2.7**",
"**2.8**", "**2.9**", "**3.0**")
df.z.values = as.data.frame(z.values)
new.m = df.z.values %>%
bind_cols(df.m)
kable(new.m,
booktabs = TRUE,
col.names = c("$Z$", "0.00","0.01", "0.02", "0.03", "0.04",
"0.05", "0.06", "0.07", "0.08", "0.09"),
escape = FALSE,
caption = "Standaard Normaalverdeling",
linesep = "",
align = c('r')) %>%
kable_styling(font_size = 10)
Try this solution:
```{r echo=FALSE, message=FALSE, warning=FALSE, include = FALSE}
library(kableExtra)
#make and save our table into working directory
table1 <- head(mtcars[1:5]) %>%
kbl() %>%
kable_styling(full_width = F) %>%
save_kable("tab_kbl.png")
#make and save our plot into working directory
png('norm_pl.png')
plot(rnorm(10))
dev.off()
```
```{r,echo=FALSE, message=FALSE, warning=FALSE, fig.cap="My image", fig.align = "center"}
library(cowplot)
#combine our images in the one
img1 <- ggdraw() + draw_image("norm_pl.png", scale = 1)
img2 <- ggdraw() + draw_image("tab_kbl.png", scale = 1)
plot_grid(img1, img2)
```
An another variant
```{r, fig.align='center', fig.cap="My beautiful image"}
library(gridExtra)
library(grid)
library(cowplot)
t1 <- tableGrob(head(mtcars[1:5]), theme = ttheme_minimal())
p2 <- ggplot(mtcars, aes(cyl, mpg)) +
geom_point()
plot_grid(t1, p2, ncol = 2, rel_widths = c(2,1))
```

delete_part deletes the top border when outputting pdf

I am using the following rmarkdown code, using xelatex engine:
access <- function(x, ...) {
x <- delete_part(x)
x <- colformat_double(x, big.mark = "'", decimal.mark = ",")
x <- set_table_properties(x, layout = "autofit")
x <- border_remove(x)
std_border <- fp_border_default(width = 1, color = "black")
x <- border_outer(x, part="all", border = std_border )
x <- border_inner_h(x, border = std_border, part="all")
x <- border_inner_v(x, border = std_border, part="all")
autofit(x)
}
firstc <- c("Field:","Table:","Sort:","Show:","Criteria:","Or:")
secondc <- c("Field:","Table:","Sort:","Show:","Criteria:","Or:")
```
```{r echo=FALSE}
tabela <- data.frame(firstc,secondc)
ft <- flextable(tabela)
ft <- access(ft)
ft <- hline_top(ft)
ft <- fit_to_width(ft, max_width = 4)
ft <- set_table_properties(ft, layout = "autofit", width = 1)
ft
```
However, the top hline does not show up in the PDF output.
Any ideas?

Multiple Flextables in RMarkdown chunk (with echo = F) do not render

I am using R 3.5.1 on OS Windows 7 x64.
My package versions are:
flextable: 0.5.1
officer: 0.3.2
tidyverse: 1.2.1
tidyr: 0.8.2
I am trying to create and then print multiple flextables in a single chunk to Word. I also do not want the actual R code in the Word Doc, so I've set echo = FALSE. However, I've run into something strange.
If I use the following code (echo = T):
```{r, echo = F, warning=FALSE, message=FALSE}
library(tidyverse)
library(flextable)
library(officer)
```
```{r, echo = T}
iris_data <- head(iris, n = 10)
iris_data_ft <- iris_data %>% flextable() %>%
hline(part = 'header', border = fp_border(color = "black", width = 3)) %>%
align(align ='center', part = 'all') %>%
align(j = 1, align ='left', part = 'all') %>%
add_header_lines('this is a test')
iris_data_ft
iris_data2 <- tail(iris, n = 10)
iris_data2_ft <- iris_data2 %>% flextable() %>%
hline(part = 'header', border = fp_border(color = "black", width = 3)) %>%
align(align ='center', part = 'all') %>%
align(j = 1, align ='left', part = 'all') %>%
add_header_lines('this is a test')
iris_data2_ft
```
I get the following output of proper flextables in Word:
If I use the exact same code, but with echo = F:
```{r, echo = F}
iris_data <- head(iris, n = 10)
iris_data_ft <- iris_data %>% flextable() %>%
hline(part = 'header', border = fp_border(color = "black", width = 3)) %>%
align(align ='center', part = 'all') %>%
align(j = 1, align ='left', part = 'all') %>%
add_header_lines('this is a test')
iris_data_ft
iris_data2 <- tail(iris, n = 10)
iris_data2_ft <- iris_data2 %>% flextable() %>%
hline(part = 'header', border = fp_border(color = "black", width = 3)) %>%
align(align ='center', part = 'all') %>%
align(j = 1, align ='left', part = 'all') %>%
add_header_lines('this is a test')
iris_data2_ft
```
I get the following in Word (this goes on for 58 pages):
Finally, if I split the one chunk for the two flextables into two separate chunks and set echo = F:
```{r, echo = F}
iris_data <- head(iris, n = 10)
iris_data_ft <- iris_data %>% flextable() %>%
hline(part = 'header', border = fp_border(color = "black", width = 3)) %>%
align(align ='center', part = 'all') %>%
align(j = 1, align ='left', part = 'all') %>%
add_header_lines('this is a test')
iris_data_ft
```
```{r, echo = F}
iris_data2 <- tail(iris, n = 10)
iris_data2_ft <- iris_data2 %>% flextable() %>%
hline(part = 'header', border = fp_border(color = "black", width = 3)) %>%
align(align ='center', part = 'all') %>%
align(j = 1, align ='left', part = 'all') %>%
add_header_lines('this is a test')
iris_data2_ft
```
The tables render just fine:
While I don't mind separating the flextables into different chunks, I am wondering why this is happening. Any guidance would be greatly appreciated. Thanks!
Here is a workaround:
---
title: "Untitled"
output: word_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(flextable)
```
```{r echo=FALSE, results='asis'}
library(htmltools)
ft <- flextable(head(iris))
for(i in 1:3){
cat("```{=openxml}\n")
cat(format(ft, type = "wml"), "\n")
cat("```\n")
}
```
I guess this issue is solved with newer versions of flextable already. If I put the code following two chunks into a .Rmd document and knit to word it compiles without problems and shows tables, even if put into one chunk with echo = F. Just wanted to add: In some cases it might be helpful to add results='asis' - the 'as is'-option (raw Markdown parsing) - to your chunk header to prevent errors when parsing tables, check: bookdown.org/results-as-is.
```{r, echo = F, warning=FALSE, message=FALSE}
library(tidyverse)
library(flextable)
library(officer)
```
```{r, echo = F}
iris_data <- head(iris, n = 10)
iris_data_ft <- iris_data %>% flextable() %>%
hline(part = 'header', border = fp_border(color = "black", width = 3)) %>%
align(align ='center', part = 'all') %>%
align(j = 1, align ='left', part = 'all') %>%
add_header_lines('this is a test')
iris_data_ft
iris_data2 <- tail(iris, n = 10)
iris_data2_ft <- iris_data2 %>% flextable() %>%
hline(part = 'header', border = fp_border(color = "black", width = 3)) %>%
align(align ='center', part = 'all') %>%
align(j = 1, align ='left', part = 'all') %>%
add_header_lines('this is a test')
iris_data2_ft
```