I am building flextable
objects to show tables, and sometimes I would like to add one or several indentations in the first column, where I show some rows' names.
Next I share some code to simulate some data and have a reproducible example. The true starting point of my question is ft
(Table 1):
library(dplyr)
library(flextable)
# Simulate data
g_A <- expand.grid(x = "A", y = c("A_1", "A_2"), z = c("A_1_a", "A_1_b", "A_2_a", "A_2_b"))
g_B <- expand.grid(x = "B", y = c("B_1", "B_2"), z = c("B_1_a", "B_1_b", "B_2_a", "B_2_b"))
g <- rbind(g_A, g_B)
n <- 123
set.seed(1)
df <- sample_n(g, n, replace = TRUE)
# Build table
tmp <- c(table(df$x)[1],
table(df$y)[1],
table(df$z)[1:2],
table(df$y)[2],
table(df$z)[3:4],
table(df$x)[2],
table(df$y)[3],
table(df$z)[5:6],
table(df$y)[4],
table(df$z)[7:8])
my_tab <- data.frame("tmp" = names(tmp), "counts" = tmp, "percentages" = round(tmp/n*100, 2))
# flextable operations
ft <- flextable(my_tab)
ft <- set_header_labels(ft, tmp = "")
ft <- align(ft, align = "center")
ft <- align(ft, j = 1, align = "left")
# ft
Now, I would like to indent some names in the first column. For example, to indent A_1
I have tried the following strategies:
compose(ft, i = 2, j = 1, as_paragraph(" A_1"))
compose(ft, i = 2, j = 1, as_paragraph("\t A_1"))
# Or
# colformat_char(ft, i = 2, j = 1, prefix = " ")
# colformat_char(ft, i = 2, j = 1, prefix = "\t")
But they don't work (the result is the same as in Table 1). A "second best" strategy could be the following one (Table 2):
compose(ft, i = 2, j = 1, as_paragraph("- A_1"))
# Or
# colformat_char(ft, i = 2, j = 1, prefix = "- ")
However, I would like a proper indentation.
Finally, I share Table 3, my expected final result, with an indentation in place of each "-".
Waiting for your insights!
Ciao
To indent cells in a
flextable
you can usepadding
function: