flextable/ 0000755 0001762 0000144 00000000000 14707517032 012226 5 ustar ligges users flextable/tests/ 0000755 0001762 0000144 00000000000 14707510711 013365 5 ustar ligges users flextable/tests/testthat/ 0000755 0001762 0000144 00000000000 14707517032 015230 5 ustar ligges users flextable/tests/testthat/test-dimensions.R 0000644 0001762 0000144 00000007216 14615445141 020505 0 ustar ligges users test_that("dimensions are valid", {
dummy_df <- data.frame(my_col = rep(letters[1:3], each = 2), stringsAsFactors = FALSE)
ft <- flextable(dummy_df)
dims <- dim(ft)
expect_length(dims$widths, 1)
expect_length(dims$heights, 7)
ft <- add_header(ft, my_col = "second row header")
dims <- dim(ft)
expect_length(dims$widths, 1)
expect_length(dims$heights, 8)
ft <- height_all(ft, height = .15, part = "all")
dims <- dim(ft)
expect_true(all(is.finite(dims$widths)))
expect_true(all(is.finite(dims$heights)))
typology <- data.frame(
col_keys = c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width", "Species"),
what = c("Sepal", "Sepal", "Petal", "Petal", "Species"),
measure = c("Length", "Width", "Length", "Width", "Species"),
stringsAsFactors = FALSE
)
ft <- flextable(head(iris))
ft <- set_header_df(ft, mapping = typology, key = "col_keys")
dims <- dim(ft)
expect_length(dims$widths, 5)
expect_length(dims$heights, 8)
})
test_that("autofit and dim_pretty usage", {
typology <- data.frame(
col_keys = c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width", "Species"),
what = c("Sepal", "Sepal", "Petal", "Petal", "Species"),
measure = c("Length", "Width", "Length", "Width", "Species"),
stringsAsFactors = FALSE
)
ft <- flextable(head(iris))
ft <- set_header_df(ft, mapping = typology, key = "col_keys")
ft <- autofit(ft, add_w = 0.0, add_h = 0.0)
dims <- dim(ft)
expect_true(all(is.finite(dims$widths)))
expect_true(all(is.finite(dims$heights)))
dims <- dim_pretty(ft)
expect_true(all(is.finite(dims$widths)))
expect_true(all(is.finite(dims$heights)))
})
test_that("height usage", {
dummy_df <- data.frame(
my_col1 = rep(letters[1:3], each = 2),
my_col2 = rep(letters[4:6], each = 2),
stringsAsFactors = FALSE
)
ft <- flextable(dummy_df)
dims <- dim_pretty(ft)
expect_silent({
ft <- height_all(ft, height = .25, part = "all")
})
expect_error({
ft <- height(ft, height = dims$heights[-1], part = "all")
})
expect_error({
ft <- height(ft, height = 1:3, part = "body")
})
})
test_that("width usage", {
dummy_df <- data.frame(
my_col1 = rep(letters[1:3], each = 2),
my_col2 = rep(letters[4:6], each = 2),
stringsAsFactors = FALSE
)
ft <- flextable(dummy_df)
expect_silent(width(ft, j = "my_col1", width = 1))
expect_silent(width(ft, j = 1:2, width = .7))
expect_error(width(ft, j = 1:2, width = rep(.7, 3)))
})
test_that("autofit with horizontal spans", {
dat <-
data.frame(
`Header should span 2 cols` = c("Whoooo", "Whaaaat", "Whyyyyy"),
dummy_title = c("Whoooo", "Whaaaat", "Whyyyyy"),
check.names = FALSE
)
ft <- flextable(dat)
ft <- merge_at(
x = ft, i = 1, j = 1:2,
part = "header"
)
dims_divided <- dim_pretty(ft, hspans = "divided")
dims_included <- dim_pretty(ft, hspans = "included")
expect_gt(dims_included$widths[1], dims_divided$widths[1])
dims_none <- dim_pretty(ft, hspans = "none")
dims_included_no_header <- dim_pretty(ft, hspans = "included", part = "body")
expect_equal(dims_none$widths, dims_included_no_header$widths)
})
test_that("HTML table width when autofit layout", {
x <- data.frame(
x = c(
"[-0.36, -0.01]", "[0, 0]",
"000, 000", "0000 0000"
)
)
ft <- flextable(x)
ft <- set_table_properties(
x = ft, layout = "autofit"
)
str <- flextable:::gen_raw_html(ft)
expect_false(grepl("table-layout:auto;width:", str, fixed = TRUE))
ft <- set_table_properties(
x = ft, layout = "autofit", width = .1
)
str <- flextable:::gen_raw_html(x = ft)
expect_true(grepl("table-layout:auto;width:", str, fixed = TRUE))
})
flextable/tests/testthat/test-padding.R 0000644 0001762 0000144 00000001552 14615445170 017742 0 ustar ligges users test_that("padding overwrite all paddings", {
ft <- flextable(data.frame(a = c("", ""), stringsAsFactors = FALSE))
ft <- padding(ft, padding = 5)
new_paddings <- c(
ft$body$styles$pars$padding.bottom$data[, ],
ft$body$styles$pars$padding.top$data[, ],
ft$body$styles$pars$padding.left$data[, ],
ft$body$styles$pars$padding.right$data[, ]
)
new_paddings <- unique(new_paddings)
expect_equal(new_paddings, 5)
})
test_that("padding overwrite all paddings but not missing", {
ft <- flextable(iris)
ft <- padding(ft, padding = 5, padding.top = 20)
new_paddings <- c(
ft$body$styles$pars$padding.bottom$data[, ],
ft$body$styles$pars$padding.top$data[, ],
ft$body$styles$pars$padding.left$data[, ],
ft$body$styles$pars$padding.right$data[, ]
)
new_paddings <- unique(new_paddings)
expect_equal(new_paddings, c(5, 20))
})
flextable/tests/testthat/test-text.R 0000644 0001762 0000144 00000021254 14707433005 017315 0 ustar ligges users ft1 <- flextable(data.frame(a = "1 < 3", stringsAsFactors = FALSE))
get_xml_doc <- function(tab, main_folder = "docx_folder") {
docx_file <- tempfile(fileext = ".docx")
doc <- read_docx()
doc <- body_add_flextable(doc, value = tab)
print(doc, target = docx_file)
main_folder <- file.path(getwd(), main_folder)
unlink(main_folder, recursive = TRUE, force = TRUE)
unpack_folder(file = docx_file, folder = main_folder)
doc_file <- file.path(main_folder, "/word/document.xml")
read_xml(doc_file)
}
get_xml_ppt <- function(tab, main_folder = "pptx_folder") {
pptx_file <- tempfile(fileext = ".pptx")
doc <- read_pptx()
doc <- add_slide(doc, layout = "Title and Content", master = "Office Theme")
doc <- ph_with(doc, tab, location = ph_location_type(type = "body"))
print(doc, target = pptx_file)
main_folder <- file.path(getwd(), main_folder)
unlink(main_folder, recursive = TRUE, force = TRUE)
unpack_folder(file = pptx_file, folder = main_folder)
doc_file <- file.path(main_folder, "/ppt/slides/slide1.xml")
read_xml(doc_file)
}
test_that("docx - string are html encoded", {
main_folder <- "docx_folder"
doc <- get_xml_doc(tab = ft1, main_folder = main_folder)
text_ <- xml_text(xml_find_first(doc, "w:body/w:tbl[1]/w:tr[2]/w:tc/w:p/w:r/w:t"))
expect_equal(text_, c("1 < 3"))
unlink(main_folder, recursive = TRUE, force = TRUE)
})
test_that("pptx - string are html encoded", {
main_folder <- "pptx_folder"
doc <- get_xml_ppt(tab = ft1, main_folder = main_folder)
text_ <- xml_text(xml_find_first(doc, "//a:tbl/a:tr[2]/a:tc/a:txBody/a:p/a:r/a:t"))
expect_equal(text_, c("1 < 3"))
unlink(main_folder, recursive = TRUE, force = TRUE)
})
test_that("html - string are html encoded", {
str_ <- flextable:::gen_raw_html(ft1)
str_ <- gsub("", "", str_)
str_ <- gsub("", "", str_)
str_ <- gsub("", "", str_)
str_ <- gsub("(.*)", "", str_)
str_ <- gsub("", "", str_)
str_ <- gsub("", "", str_)
str_ <- gsub("", str_, "")
doc <- read_xml(str_)
text_ <- xml_text(xml_find_all(doc, "//table/tbody/tr/td/p"))
expect_equal(text_, c("a", ""))
})
test_that("newlines and tabulations expand correctly", {
z <- flextable(data.frame(a = c("")))
z <- compose(
x = z, i = 1, j = 1,
value = as_paragraph(
"this\nis\nit",
"\n\t", "This", "\n",
"is", "\n", "it", "\n",
"this\tis\tit\nthatsit\n"
)
)
z <- delete_part(z, part = "header")
chunks_txt <- information_data_chunk(z)$txt
expect_equal(
chunks_txt,
c(
"this", "
", "is", "
", "it",
"
", "", "This", "
",
"is", "
", "it", "
", "this",
"", "is", "", "it", "
",
"thatsit", "
"
)
)
})
test_that("word superscript and subscript", {
ft <- flextable(data.frame(a = ""), col_keys = c("dummy"))
ft <- delete_part(ft, part = "header")
ft <- compose(ft,
i = 1, j = "dummy", part = "body",
value = as_paragraph(
as_sub("Sepal.Length")
)
)
runs <- information_data_chunk(ft)
expect_equal(runs$vertical.align[1], "subscript")
openxml <- flextable:::runs_as_wml(ft, txt_data = runs)$run_openxml
expect_match(openxml, "", fixed = TRUE)
ft <- compose(ft,
i = 1, j = "dummy", part = "body",
value = as_paragraph(
as_sup("Sepal.Length")
)
)
runs <- information_data_chunk(ft)
expect_equal(runs$vertical.align[1], "superscript")
openxml <- flextable:::runs_as_wml(ft, txt_data = runs)$run_openxml
expect_match(openxml, "", fixed = TRUE)
})
test_that("highlight", {
ft <- flextable(data.frame(test = "test"))
ft <- add_footer_lines(ft, values = "test")
ft <- mk_par(ft,
j = "test", part = "body",
value = as_paragraph(
as_highlight(test, color = "yellow")
)
)
ft <- mk_par(ft,
j = "test", part = "header",
value = as_paragraph(
as_highlight(test, color = "red")
)
)
ft <- mk_par(ft,
j = "test", part = "footer",
value = as_paragraph(
as_highlight(test, color = "purple")
)
)
runs <- information_data_chunk(ft)
expect_equal(runs$shading.color, c("red", "yellow", "purple"))
openxml <- flextable:::runs_as_wml(ft, txt_data = runs)$run_openxml
expect_match(openxml[1], "", fixed = TRUE)
expect_match(openxml[2], "", fixed = TRUE)
expect_match(openxml[3], "", fixed = TRUE)
openxml <- flextable:::runs_as_pml(ft)$par_nodes_str
expect_match(openxml[1], "", fixed = TRUE)
expect_match(openxml[2], "", fixed = TRUE)
expect_match(openxml[3], "", fixed = TRUE)
html_info <- flextable:::runs_as_html(ft)
css <- attr(html_info, "css")
expect_match(css, "background-color:rgba(255, 0, 0, 1.00);}", fixed = TRUE)
expect_match(css, "background-color:rgba(255, 255, 0, 1.00);}", fixed = TRUE)
expect_match(css, "background-color:rgba(160, 32, 240, 1.00);}", fixed = TRUE)
latex_str <- flextable:::runs_as_latex(ft)$txt
expect_match(latex_str[1], "\\colorbox[HTML]{FF0000}", fixed = TRUE)
expect_match(latex_str[2], "\\colorbox[HTML]{FFFF00}", fixed = TRUE)
expect_match(latex_str[3], "\\colorbox[HTML]{A020F0}", fixed = TRUE)
rtf_str <- flextable:::runs_as_rtf(ft)$txt
expect_match(rtf_str[1], "%ftshading:red%", fixed = TRUE)
expect_match(rtf_str[2], "%ftshading:yellow%", fixed = TRUE)
expect_match(rtf_str[3], "%ftshading:purple%", fixed = TRUE)
})
test_that("as_bracket", {
ft <- flextable(head(iris), col_keys = c("Species", "what"))
ft <- mk_par(ft,
j = "what", part = "body",
value = as_paragraph(
as_bracket(Sepal.Length, Sepal.Width, sep = "-")
)
)
runs <- information_data_chunk(ft)
runs <- runs[runs$.part %in% "body", ]
expect_equal(
runs$txt,
c(
"setosa", "(5.1-3.5)", "setosa", "(4.9-3)", "setosa",
"(4.7-3.2)", "setosa", "(4.6-3.1)", "setosa", "(5-3.6)",
"setosa", "(5.4-3.9)"
)
)
})
test_that("as_equation", {
skip_if_not_installed("equatags")
eqs <- c(
"(ax^2 + bx + c = 0)",
"a \\ne 0",
"x = {-b \\pm \\sqrt{b^2-4ac} \\over 2a}"
)
df <- data.frame(formula = eqs)
ft <- flextable(df)
ft <- mk_par(ft,
j = "formula", part = "body",
value = as_paragraph(as_equation(formula, width = 2, height = .5))
)
runs <- information_data_chunk(ft)
openxml <- flextable:::runs_as_wml(ft, txt_data = runs)$run_openxml
expect_match(openxml[2], "", fixed = TRUE)
expect_match(openxml[3], "", fixed = TRUE)
expect_match(openxml[4], "", fixed = TRUE)
openxml <- flextable:::runs_as_pml(ft)$par_nodes_str
expect_match(openxml[2], "", fixed = TRUE)
expect_match(openxml[3], "", fixed = TRUE)
expect_match(openxml[4], "", fixed = TRUE)
latex_str <- flextable:::runs_as_latex(ft)$txt
expect_match(latex_str[2], eqs[1], fixed = TRUE)
expect_match(latex_str[3], eqs[2], fixed = TRUE)
expect_match(latex_str[4], eqs[3], fixed = TRUE)
runs <- information_data_chunk(ft)
html_str <- flextable:::runs_as_html(ft)$span_tag
expect_match(html_str[2], "", fixed = TRUE)
expect_match(html_str[3], "", fixed = TRUE)
expect_match(html_str[4], "", fixed = TRUE)
})
test_that("as_word_field", {
ft <- flextable(head(cars))
ft <- add_footer_lines(ft, "temp text")
ft <- compose(
x = ft, part = "footer", i = 1, j = 1,
as_paragraph(
as_word_field(x = "Page", width = .05)
)
)
runs <- information_data_chunk(ft)
wml_str <- flextable:::runs_as_wml(ft)
wml_str <- wml_str[wml_str$.part %in% "footer",]$run_openxml[1]
expect_match(wml_str, "Page", fixed = TRUE)
})
flextable/tests/testthat/test-keep_next.R 0000644 0001762 0000144 00000001441 14615445132 020311 0 ustar ligges users init_flextable_defaults()
iris_sum <- summarizor(iris, by = "Species")
ft_1 <- as_flextable(iris_sum, sep_w = 0)
ft_1 <- set_caption(ft_1, "a caption")
test_that("docx-keep-with-next", {
tmp_file <- tempfile(fileext = ".docx")
docx <- read_docx()
docx <- body_add_flextable(docx, ft_1)
for(i in 1:10) {
docx <- body_add_par(docx, value = "")
}
ft_1 <- paginate(ft_1, init = TRUE, hdr_ftr = TRUE)
docx <- body_add_flextable(docx, ft_1)
print(docx, target = tmp_file)
doc <- read_docx(path = tmp_file)
body_xml <- docx_body_xml(doc)
expect_length(
xml_find_all(body_xml, "//w:tbl[1]/w:tr/w:tc/w:p/w:pPr/w:keepNext"),
n = 0
)
expect_length(
xml_find_all(body_xml, "//w:tbl[2]/w:tr/w:tc/w:p/w:pPr/w:keepNext"),
n = 65
)
})
init_flextable_defaults()
flextable/tests/testthat/test-merge.R 0000644 0001762 0000144 00000003125 14615445144 017432 0 ustar ligges users test_that("identical values within columns are merged", {
dummy_df <- data.frame(values = rep(letters[1:3], each = 2), stringsAsFactors = FALSE)
ft <- flextable(dummy_df)
ft <- merge_v(x = ft, j = "values")
expect_equal(ft$body$spans$columns[, 1], rep(c(2, 0), 3), ignore_attr = TRUE)
})
test_that("identical values within rows are merged", {
dummy_df <- data.frame(
col1 = letters,
col2 = letters,
stringsAsFactors = FALSE
)
ft <- flextable(dummy_df)
ft <- merge_h(x = ft)
ref <- matrix(c(rep(2, 26), rep(0, 26)), ncol = 2)
expect_equal(ft$body$spans$rows, ref, ignore_attr = TRUE)
})
test_that("span at", {
dummy_df <- data.frame(
col1 = letters,
col2 = letters,
stringsAsFactors = FALSE
)
ft <- flextable(dummy_df)
ft <- merge_at(x = ft, i = 1:4, j = 1:2)
ref <- matrix(c(rep(2, 4), rep(1, 22), rep(0, 4), rep(1, 22)), ncol = 2)
expect_equal(ft$body$spans$rows, ref, ignore_attr = TRUE)
ref <- matrix(c(4, rep(0, 3), rep(1, 22), 4, rep(0, 3), rep(1, 22)), ncol = 2)
expect_equal(ft$body$spans$columns, ref, ignore_attr = TRUE)
})
test_that("merged cells can be un-merged", {
dummy_df <- data.frame(
col1 = rep("a", 5),
col2 = rep("a", 5),
stringsAsFactors = FALSE
)
ft <- flextable(dummy_df)
ft <- merge_h(x = ft)
expect_true(all(ft$body$spans$rows[, 1] == 2))
ft <- merge_none(ft)
expect_true(all(ft$body$spans$rows == 1))
ft <- merge_v(x = ft)
expect_true(all(ft$body$spans$columns[1, ] == 5))
expect_true(all(ft$body$spans$columns[-1, ] == 0))
ft <- merge_none(ft)
expect_true(all(ft$body$spans$columns == 1))
})
flextable/tests/testthat/test-captions-rmd.R 0000644 0001762 0000144 00000014453 14653400117 020732 0 ustar ligges users init_flextable_defaults()
rmd_file_0 <- "rmd/captions.Rmd"
if (!file.exists(rmd_file_0)) { # just for dev purpose
rmd_file_0 <- "tests/testthat/rmd/captions.Rmd"
}
rmd_file <- tempfile(fileext = ".Rmd")
file.copy(rmd_file_0, rmd_file, overwrite = TRUE)
html_file <- gsub("\\.Rmd$", ".html", rmd_file)
docx_file <- gsub("\\.Rmd$", ".docx", rmd_file)
pdf_file <- gsub("\\.Rmd$", ".pdf", rmd_file)
test_that("with html_document", {
unlink(html_file, force = TRUE)
render(rmd_file,
output_format = rmarkdown::html_document(),
output_file = html_file,
envir = new.env(),
quiet = TRUE
)
xml_doc <- get_html_xml(html_file)
# id is there, caption is the one of set_caption, no numbering
caption_id2 <- xml_find_first(xml_doc, "//table/caption[@id='id2']")
expect_true(grepl("text-align:center;", xml_attr(caption_id2, "style")))
expect_equal(xml_text(caption_id2), "azerty querty")
# first_chunk has an defined class
first_chunk_class <- xml_attr(xml_child(caption_id2, 1), "class")
expect_true(grepl("^cl\\-", first_chunk_class))
expect_true(any(grepl(first_chunk_class, xml_text(xml_find_all(xml_doc, "//style")))))
crossref_chunk <- xml_find_first(xml_doc, "//a[@href='#tab:id1']")
expect_true(inherits(crossref_chunk, "xml_missing"))
body <- xml_find_first(xml_doc, "//*[id='tab:id1']")
id_chunk <- xml_find_first(xml_doc, "//table/caption/p/span[@id='tab:id1']")
expect_true(inherits(id_chunk, "xml_missing"))
captions <- xml_find_all(xml_doc, "//table/caption/p")
expect_true(all(!grepl("Table [0-9]+:", xml_text(captions))))
})
test_that("with html_document2", {
skip_if_not_installed("bookdown")
unlink(html_file, force = TRUE)
render(rmd_file,
output_format = bookdown::html_document2(keep_md = FALSE),
output_file = html_file,
envir = new.env(),
quiet = TRUE
)
xml_doc <- get_html_xml(html_file)
# id is there, caption is the one of set_caption, numbering
caption_id2 <- xml_find_first(xml_doc, "//table/caption/span[@id='tab:id2']")
expect_true(grepl("text-align:center;", xml_attr(xml_parent(caption_id2), "style")))
expect_true(grepl("Table [0-9]+\\: azerty querty", xml_text(xml_parent(caption_id2))))
# first_chunk has an defined class
first_chunk_class <- xml_attr(xml_siblings(caption_id2), "class")
expect_true(all(grepl("^cl\\-", first_chunk_class)))
crossref_chunk <- xml_find_first(xml_doc, "//a[@href='#tab:id1']")
expect_false(inherits(crossref_chunk, "xml_missing"))
id_chunk <- xml_find_first(xml_doc, "//caption/span[@id='tab:id1']")
expect_false(inherits(id_chunk, "xml_missing"))
caption <- xml_find_first(xml_doc, "//caption[span/@id='tab:id1']")
expect_true(grepl("Table 2:", xml_text(caption)))
})
test_that("with word_document", {
skip_if(pandoc_version() == numeric_version("2.9.2.1"))
unlink(docx_file, force = TRUE)
render(rmd_file,
output_format = rmarkdown::word_document(keep_md = FALSE),
output_file = docx_file,
envir = new.env(),
quiet = TRUE
)
doc <- get_docx_xml(docx_file)
caption_node <- xml_find_first(doc,
xpath = "/w:document/w:body/w:tbl[4]/preceding-sibling::*[1]"
)
expect_false(grepl("Table [1-5]+", xml_text(caption_node), fixed = TRUE))
style_nodes <- xml_find_all(doc, "//w:pStyle[@w:val='TableCaption']")
expect_length(style_nodes, 4)
expect_true(all(xml_attr(style_nodes, "val") %in% "TableCaption"))
txt_nodes <- xml_parent(xml_parent(style_nodes))
expect_true(
all(!grepl("^Table [1-5]+\\:", xml_text(txt_nodes)))
)
bookmarks <- xml_find_all(doc, "//w:tbl/preceding-sibling::w:p[1]/w:bookmarkStart")
expect_length(bookmarks, 0)
})
test_that("with word_document2", {
skip_if(pandoc_version() <= numeric_version("2.7.3"))
skip_if(pandoc_version() == numeric_version("2.9.2.1"))
skip_if_not_installed("bookdown")
unlink(docx_file, force = TRUE)
render(rmd_file,
output_format = bookdown::word_document2(keep_md = FALSE),
output_file = docx_file,
envir = new.env(),
quiet = TRUE
)
doc <- get_docx_xml(docx_file)
caption_node <- xml_find_first(doc,
xpath = "/w:document/w:body/w:tbl[2]/preceding-sibling::*[1]"
)
expect_true(grepl("Table 2", xml_text(caption_node), fixed = TRUE))
crossref_node <- xml_find_first(doc, "/w:document/w:body/w:p[2]")
expect_equal("Cross-reference is there: 2", xml_text(crossref_node))
style_nodes <- xml_find_all(doc, "//w:pStyle[@w:val='TableCaption']")
expect_length(style_nodes, 4)
expect_true(all(xml_attr(style_nodes, "val") %in% "TableCaption"))
txt_nodes <- xml_parent(xml_parent(style_nodes))
expect_true(
all(
grepl("^Table [1-4]+\\:", xml_text(txt_nodes))
)
)
bookmarks <- xml_find_all(doc, "//w:tbl/preceding-sibling::w:p[1]/w:bookmarkStart")
expect_length(bookmarks, 3)
})
test_that("word with officer", {
unlink(docx_file, force = TRUE)
ft <- flextable(head(cars))
ft <- theme_vanilla(ft)
ft <- autofit(ft)
ft <- set_caption(
x = ft,
caption = as_paragraph(
as_chunk("azerty ", props = fp_text_default(color = "cyan")),
as_chunk("querty", props = fp_text_default(color = "orange"))
),
autonum = run_autonum(seq_id = "tab", bkm = "id2"),
fp_p = fp_par(
padding = 10,
border = fp_border_default(color = "red", width = 1)
)
)
doc <- get_docx_xml(ft)
caption_node <- xml_find_first(doc,
xpath = "/w:document/w:body/w:tbl/preceding-sibling::*[1]"
)
expect_false(grepl("Table [1-5]+", xml_text(caption_node), fixed = TRUE))
style_nodes <- xml_find_all(doc, "//w:pStyle[@w:val='TableCaption']")
expect_length(style_nodes, 1)
expect_true(all(xml_attr(style_nodes, "val") %in% "TableCaption"))
bookmarks <- xml_find_all(doc, "//w:tbl/preceding-sibling::w:p[1]/w:bookmarkStart")
expect_length(bookmarks, 1)
expect_equal(xml_attr(bookmarks, "name"), "id2")
})
test_that("with pdf_document2", {
skip_if(pandoc_version() <= numeric_version("2.7.3"))
skip_if_not_installed("bookdown")
skip_if_not_installed("pdftools")
require("pdftools")
sucess <- render_rmd(file = pdf_file, rmd_format = bookdown::pdf_document2(keep_md = FALSE))
if (sucess) {
doc <- get_pdf_text(pdf_file, extract_fun = pdftools::pdf_text)
expect_true(any(grepl("Cross-reference is there: 2", doc, fixed = TRUE)))
} else {
expect_false(sucess) # only necessary to avoid a note
}
})
init_flextable_defaults()
flextable/tests/testthat/test-images.R 0000644 0001762 0000144 00000010650 14702024446 017574 0 ustar ligges users data <- iris[c(1:3, 51:53, 101:104), ]
col_keys <- c("Species", "sep_1", "Sepal.Length", "Sepal.Width", "sep_2", "Petal.Length", "Petal.Width")
img.file <- file.path(R.home("doc"), "html", "logo.jpg")
rlogo <- tempfile(fileext = ".jpg")
file.copy(img.file, rlogo)
test_that("images", {
ft <- flextable(data, col_keys = col_keys)
ft <- compose(ft,
j = "Sepal.Length",
value = as_paragraph(
as_chunk("blah blah "),
as_image(rlogo, width = .3, height = 0.23), " ",
as_chunk(sprintf("val: %.1f", Sepal.Length), props = fp_text(color = "orange", vertical.align = "superscript"))
)
)
ft <- compose(ft,
j = "sep_1",
value = as_paragraph(
as_image(rlogo, width = .3, height = 0.23)
)
)
ft <- compose(ft,
j = "Petal.Length",
value = as_paragraph(
"blah blah ",
as_chunk(Sepal.Length, props = fp_text(color = "orange", vertical.align = "superscript"))
)
)
ft <- style(ft,
pr_c = fp_cell(margin = 0, border = fp_border(width = 0)),
pr_p = fp_par(padding = 0, border = fp_border(width = 0)),
pr_t = fp_text(font.size = 10), part = "all"
)
ft <- autofit(ft, add_w = 0, add_h = 0)
dims <- ft$body$colwidths
expect_equal(as.vector(dims["sep_1"]), .3, tolerance = .00001)
docx_file <- tempfile(fileext = ".docx")
doc <- read_docx()
doc <- body_add_flextable(doc, value = ft)
expect_error(
{
print(doc, target = docx_file)
},
NA
)
})
plot1 <- tempfile(fileext = ".png")
plot2 <- tempfile(fileext = ".png")
ragg::agg_png(filename = plot1, width = 300, height = 300, units = "px")
plot(1:15, 1:15)
dev.off()
ragg::agg_png(filename = plot2, width = 300, height = 300, units = "px")
plot(1:150, 1:150)
dev.off()
df <- data.frame(
plot = c(plot1, plot2)
)
test_that("multiple images", {
skip_if_not_installed("magick")
ft <- flextable(df)
ft <- mk_par(ft, j = "plot", value = as_paragraph(as_image(rlogo, width = .3, height = 0.23)), part = "header")
ft <- mk_par(ft, j = "plot", value = as_paragraph(as_image(plot, guess_size = TRUE)))
chunk_info <- flextable::information_data_chunk(ft)
expect_equal(chunk_info$img_data, c(rlogo, df$plot))
expect_equal(chunk_info$width, c(.3, 300 / 72, 300 / 72))
expect_equal(chunk_info$height, c(.23, 300 / 72, 300 / 72))
docx_path <- save_as_docx(ft, path = tempfile(fileext = ".docx"))
doc <- read_docx(docx_path)
images_path <- doc$doc_obj$relationship()$get_images_path()
expect_equal(
gsub("([a-z0-9]+)(\\.png|\\.jpg)$", "\\2", basename(images_path)),
c(".jpg", ".png", ".png")
)
html_path <- save_as_html(ft, path = tempfile(fileext = ".html"))
doc <- read_html(html_path)
all_imgs <- xml_find_all(doc, "//img")
src_imgs <- xml_attr(all_imgs, "src")
expect_length(src_imgs, 3)
if (length(src_imgs) == 3) {
expect_match(
src_imgs[1],
"data:image/jpeg",
fixed = TRUE
)
expect_match(
src_imgs[2],
"data:image/png",
fixed = TRUE
)
expect_match(
src_imgs[3],
"data:image/png",
fixed = TRUE
)
}
zz <- gen_grob(ft)
expect_s3_class(zz$children$cell_1_1$children$contents$ftgrobs[[1]], "rastergrob")
expect_s3_class(zz$children$cell_2_1$children$contents$ftgrobs[[1]], "rastergrob")
expect_s3_class(zz$children$cell_3_1$children$contents$ftgrobs[[1]], "rastergrob")
ft <- flextable(df)
ft <- colformat_image(ft, j = "plot", width = 300 / 72, height = 300 / 72)
zz <- gen_grob(ft)
expect_s3_class(zz$children$cell_1_1$children$contents$ftgrobs[[1]], "text")
expect_s3_class(zz$children$cell_2_1$children$contents$ftgrobs[[1]], "rastergrob")
expect_s3_class(zz$children$cell_3_1$children$contents$ftgrobs[[1]], "rastergrob")
})
test_that("minibar", {
ft <- flextable(data.frame(n = 1:2))
ft <- mk_par(
ft,
j = 1,
value = as_paragraph(
minibar(value = n, max = 10, width = .5, barcol = "red", bg = "yellow")
),
part = "body"
)
minibar1 <- flextable::information_data_chunk(ft)$img_data[[2]]
expect_s3_class(minibar1, "raster")
expect_equal(nrow(minibar1), 1)
expect_equal(ncol(minibar1), 36)
expect_equal(minibar1[1:3], rep("#FF0000", 3))
expect_equal(minibar1[4:36], rep("#FFFF00", 33))
minibar2 <- flextable::information_data_chunk(ft)$img_data[[3]]
expect_s3_class(minibar2, "raster")
expect_equal(nrow(minibar2), 1)
expect_equal(ncol(minibar2), 36)
expect_equal(minibar2[1:7], rep("#FF0000", 7))
expect_equal(minibar2[8:36], rep("#FFFF00", 29))
})
flextable/tests/testthat/test-pptx-tables.R 0000644 0001762 0000144 00000003040 14615445172 020573 0 ustar ligges users test_that("row height is valid", {
ft <- flextable(head(iris))
pptx_file <- "test.pptx"
doc <- read_pptx()
doc <- add_slide(doc, layout = "Title and Content", master = "Office Theme")
doc <- ph_with(doc, value = ft, location = ph_location_type(type = "body"))
doc <- print(doc, target = pptx_file)
main_folder <- file.path(getwd(), "pptx_folder")
unzip(pptx_file, exdir = main_folder)
slide_file <- file.path(main_folder, "/ppt/slides/slide1.xml")
doc <- read_xml(slide_file)
nodes <- xml_find_all(doc, "//p:graphicFrame/a:graphic/a:graphicData/a:tbl/a:tr")
h_values <- sapply(nodes, xml_attr, attr = "h")
h_values <- as.integer(h_values)
expect_true(all(is.finite(h_values)))
expect_true(all(h_values > 0))
unlink(main_folder, recursive = TRUE, force = TRUE)
unlink(pptx_file, force = TRUE)
})
test_that("location is correct", {
ft <- flextable(head(iris))
pptx_file <- tempfile(fileext = ".pptx")
doc <- read_pptx()
doc <- add_slide(doc, layout = "Title and Content", master = "Office Theme")
doc <- ph_with(doc, value = ft, location = ph_location(left = 0, top = 0))
doc <- print(doc, target = pptx_file)
main_folder <- file.path(getwd(), "pptx_folder")
unpack_folder(file = pptx_file, folder = main_folder)
slide_file <- file.path(main_folder, "/ppt/slides/slide1.xml")
doc <- read_xml(slide_file)
node <- xml_find_first(doc, "//p:graphicFrame/p:xfrm/a:off")
expect_equal(xml_attr(node, "x"), "0")
expect_equal(xml_attr(node, "y"), "0")
unlink(main_folder, recursive = TRUE, force = TRUE)
})
flextable/tests/testthat/test-new-rows.R 0000644 0001762 0000144 00000015361 14615445417 020124 0 ustar ligges users test_that("nrow_part or ncol_keys checks", {
expect_error(nrow_part(12))
expect_error(ncol_keys(12))
ft <- flextable(head(iris))
expect_equal(nrow_part(ft, part = "footer"), 0)
expect_equal(nrow_part(ft, part = "body"), 6)
expect_equal(ncol_keys(ft), 5)
})
test_that("add lines", {
ft <- flextable(head(iris))
newvals <- c("A", "B", "C", "D")
ft <- add_header_lines(
x = ft,
values = newvals,
top = TRUE)
expect_equal(nrow_part(ft, part = "header"), 5)
ft <- add_footer_lines(
x = ft,
values = newvals,
top = FALSE)
expect_equal(nrow_part(ft, part = "footer"), 4)
x <- information_data_chunk(ft)
header_sel <- x[x$.part %in% "header",]
expect_equal(
header_sel$txt,
c(
rep(newvals, each = 5),
colnames(iris)
)
)
footer_sel <- x[x$.part %in% "footer",]
expect_equal(
footer_sel$txt,
rep(newvals, each = 5)
)
})
test_that("separate_header", {
x <- data.frame(
Species = as.factor(c("setosa", "versicolor", "virginica")),
Sepal.Length_mean_zzz = c(5.006, 5.936, 6.588),
Sepal.Length_sd = c(0.35249, 0.51617, 0.63588),
Sepal.Width_mean = c(3.428, 2.77, 2.974),
Sepal.Width_sd_sfsf_dsfsdf = c(0.37906, 0.3138, 0.3225),
Petal.Length_mean = c(1.462, 4.26, 5.552),
Petal.Length_sd = c(0.17366, 0.46991, 0.55189),
Petal.Width_mean = c(0.246, 1.326, 2.026),
Petal.Width_sd = c(0.10539, 0.19775, 0.27465)
)
ft_1 <- flextable(x)
ft_1 <- separate_header(x = ft_1,
opts = c("span-top", "bottom-vspan")
)
header_txt <- information_data_chunk(ft_1) |>
subset(.part %in% "header")
expect_equal(
object = header_txt$txt,
expected =
c("Species", "Sepal", "Sepal", "Sepal", "Sepal", "Petal", "Petal",
"Petal", "Petal", "", "Length", "Length", "Width", "Width", "Length",
"Length", "Width", "Width", "", "mean", "sd", "mean", "sd", "mean",
"sd", "mean", "sd", "", "zzz", "", "", "sfsf", "", "", "", "",
"", "", "", "", "dsfsdf", "", "", "", "")
)
})
test_that("add part rows", {
ft01 <- fp_text_default(color = "red")
ft02 <- fp_text_default(color = "orange")
pars <- as_paragraph(
as_chunk(c("(1)", "(2)"), props = ft02), " ",
as_chunk(c(
"My tailor is rich",
"My baker is rich"
), props = ft01)
)
ft_1 <- flextable(head(mtcars))
ft_1 <- add_header_row(ft_1,
values = pars,
colwidths = c(5, 6), top = FALSE
)
ft_1 <- add_body_row(ft_1,
values = pars,
colwidths = c(5, 6), top = TRUE
)
ft_1 <- add_footer_row(ft_1,
values = pars,
colwidths = c(3, 8), top = FALSE
)
x <- information_data_chunk(ft_1)
new_header_sel <- x[x$.part %in% "header" &
x$.row_id %in% 2 &
x$.col_id %in% "mpg",]
expect_equal(new_header_sel$txt, c("(1)", " ", "My tailor is rich"))
expect_equal(new_header_sel$color, c("orange", "black", "red"))
new_header_sel <- x[x$.part %in% "header" &
x$.row_id %in% 2 &
x$.col_id %in% "wt",]
expect_equal(new_header_sel$txt, c("(2)", " ", "My baker is rich"))
expect_equal(new_header_sel$color, c("orange", "black", "red"))
spans <- flextable:::fortify_span(ft_1, parts = "header")
expect_equal(
spans$rowspan,
c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
5, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0)
)
expect_true(all(spans$colspan %in% 1))
expect_equal(
colSums(is.na(ft_1$header$dataset)),
rep(0L, ncol(mtcars)),
ignore_attr = TRUE
)
new_body_sel <- x[x$.part %in% "body" &
x$.row_id %in% 1 &
x$.col_id %in% "mpg",]
expect_equal(new_body_sel$txt, c("(1)", " ", "My tailor is rich"))
expect_equal(new_body_sel$color, c("orange", "black", "red"))
new_body_sel <- x[x$.part %in% "body" &
x$.row_id %in% 1 &
x$.col_id %in% "wt",]
expect_equal(new_body_sel$txt, c("(2)", " ", "My baker is rich"))
expect_equal(new_body_sel$color, c("orange", "black", "red"))
spans <- flextable:::fortify_span(ft_1, parts = "body")
spans <- spans[spans$.row_id %in% 1,]
expect_equal(
spans$rowspan,
c(5, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0)
)
expect_true(all(spans$colspan %in% 1))
expect_equal(
colSums(is.na(ft_1$body$dataset)),
rep(1L, ncol(mtcars)),
ignore_attr = TRUE
)
new_footer_sel <- x[x$.part %in% "footer" &
x$.row_id %in% 1 &
x$.col_id %in% "mpg",]
expect_equal(new_footer_sel$txt, c("(1)", " ", "My tailor is rich"))
new_footer_sel <- x[x$.part %in% "footer" &
x$.row_id %in% 1 &
x$.col_id %in% "hp",]
expect_equal(new_header_sel$txt, c("(2)", " ", "My baker is rich"))
spans <- flextable:::fortify_span(ft_1, parts = "footer")
expect_equal(
spans$rowspan,
c(3, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0)
)
expect_true(all(spans$colspan %in% 1))
expect_equal(
colSums(is.na(ft_1$footer$dataset)),
rep(0L, ncol(mtcars)),
ignore_attr = TRUE
)
})
test_that("add rows", {
ft <- flextable(head(iris),
col_keys = c(
"Species", "Sepal.Length", "Petal.Length",
"Sepal.Width", "Petal.Width"
)
)
fun <- function(x) {
paste0(
c("min: ", "max: "),
formatC(range(x))
)
}
new_row <- list(
Sepal.Length = fun(iris$Sepal.Length),
Sepal.Width = fun(iris$Sepal.Width),
Petal.Width = fun(iris$Petal.Width),
Petal.Length = fun(iris$Petal.Length)
)
ft <- add_header(ft, values = new_row, top = FALSE)
ft <- add_body(
x = ft, Sepal.Length = 1:5,
Sepal.Width = 1:5 * 2, Petal.Length = 1:5 * 3,
Petal.Width = 1:5 + 10, Species = "Blah", top = FALSE
)
x <- information_data_chunk(ft)
new_row_sel <- x[x$.part %in% "body" &
x$.row_id %in% 7:11 &
x$.col_id %in% "Species",]
expect_equal(new_row_sel$txt, rep("Blah", 5))
new_row_sel <- x[x$.part %in% "body" &
x$.row_id %in% 7:11 &
x$.col_id %in% "Sepal.Length",]
expect_equal(new_row_sel$txt, as.character(1:5))
expect_true(is.factor(ft$body$dataset[7:11,]$Species))
expect_equal(levels(ft$body$dataset[7:11,]$Species), c("setosa", "versicolor", "virginica", "Blah"))
expect_equal(as.character(ft$body$dataset[7:11,]$Species), rep("Blah", 5))
expect_equal(ft$body$dataset[7:11,]$Sepal.Length, 1:5)
new_header_sel <- x[x$.part %in% "header" &
x$.row_id %in% 2:3 &
x$.col_id %in% "Sepal.Width",]
expect_equal(new_header_sel$txt, c("min: 2", "max: 4.4"))
new_header_sel <- x[x$.part %in% "header" &
x$.row_id %in% 2:3 &
x$.col_id %in% "Species",]
expect_equal(new_header_sel$txt, c("", ""))
})
flextable/tests/testthat/rmd/ 0000755 0001762 0000144 00000000000 14653400117 016005 5 ustar ligges users flextable/tests/testthat/rmd/captions.Rmd 0000644 0001762 0000144 00000002347 14311145233 020273 0 ustar ligges users ---
title: none
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(flextable)
library(magrittr)
library(officer)
caption_md <- "This is a caption"
knitr::opts_chunk$set(ft.shadow = FALSE,
tab.lp = "tab:",
tab.cap.style = "Table Caption")
ft <- flextable(head(cars)) %>%
theme_vanilla() %>%
autofit()
```
Cross-reference is there: \@ref(tab:id1)
## A caption, no id
```{r tab.cap=caption_md}
ft
```
## A caption and an id
```{r tab.cap=caption_md, label="id1"}
ft
```
## No caption and an id
```{r tab.id="tab3"}
ft
```
## Using set caption
```{r table2}
#| tab.topcaption: true
set_caption(
x = ft,
caption = as_paragraph(
as_chunk("azerty ", props = fp_text_default(color = "cyan")),
as_chunk("querty", props = fp_text_default(color = "orange"))
),
autonum = run_autonum(seq_id = "tab", bkm = "id2"),
fp_p = fp_par(
padding = 10,
border = fp_border_default(color = "red", width = 1))
)
```
## Using set caption and chunk options
```{r label="id3"}
#| tab.topcaption: false
set_caption(
x = ft,
caption = as_paragraph(
as_chunk("azerty ", props = fp_text_default(color = "cyan")),
as_chunk("querty", props = fp_text_default(color = "orange"))
)
)
```
flextable/tests/testthat/rmd/borders.Rmd 0000644 0001762 0000144 00000006313 14412064416 020115 0 ustar ligges users ---
title: 'borders examples'
---
```{r include=FALSE}
library(knitr)
library(officedown)
library(flextable)
opts_chunk$set(
echo = FALSE,
ft.tabcolsep = 3
)
```
## Blah
```{r}
dat <- tibble::tribble(
~S, ~T, ~U, ~V, ~W, ~X, ~Y, ~Z,
"AA", "AA", "AA", "AA", "AA", "AA", "AA", "AA",
"BB", "AA", "AA", "AA", "AA", "AA", "AA", "AA",
"CC", "CC", "AA", "AA", "AA", "AA", "AA", "AA",
"DD", "DD", "DD", "AA", "AA", "AA", "AA", "AA",
"EE", "EE", "EE", "EE", "AA", "AA", "AA", "AA",
"FF", "FF", "FF", "FF", "FF", "AA", "AA", "AA",
"GG", "GG", "GG", "GG", "GG", "GG", "AA", "AA",
"HH", "HH", "HH", "HH", "HH", "HH", "HH", "AA"
)
ft <- flextable(dat)
ft <- theme_vader(ft)
ft <- border_outer(ft, border = fp_border_default(width = 2.5, color = "red"))
ft <- border_inner_v(ft, border = fp_border_default(width = 1, color = "cyan"))
ft <- border_inner_h(ft, border = fp_border_default(width = 1, color = "orange"))
ft <- merge_h(ft)
ft <- fix_border_issues(ft)
ft
```
## Blah
```{r}
ft <- flextable(head(iris, n = 2))
ft <- border_inner_v(ft, part = "all")
ft <- hline(ft,
i = 1, j = 2:4, part = "body",
border = officer::fp_border("red")
)
ft <- hline(ft,
i = 1, j = 1:1, part = "body",
border = officer::fp_border("orange")
)
ft <- autofit(ft)
ft
```
\pagebreak
## Blah
```{r}
dat <- data.frame(
s = c("a", "a", "a", "a", "b", "b", "b", "b"),
t = c("AA", "AA", "AA", "BB", "BB", "BB", "CC", "CC"),
u = c("DD", "DD", "DD", "DD", "DD", "DD", "DD", "DD"),
v = c("DD", "EE", "EE", "DD", "EE", "EE", "EE", "DD"),
w = c("DD", "EE", "EE", "DD", "EE", "EE", "EE", "DD"),
x = c("DD", "DD", "DD", "DD", "DD", "DD", "DD", "DD")
)
ft <- flextable(dat)
ft <- border_outer(ft, border = fp_border_default(width = 2.5, color = "red"))
ft <- border_inner_v(ft, border = fp_border_default(width = 1, color = "cyan"))
ft <- border_inner_h(ft, border = fp_border_default(width = 1, color = "orange"))
ft <- merge_v(ft, j = 1:2)
ft <- merge_h(ft)
ft <- fix_border_issues(ft)
ft
```
## Blah
```{r}
ft <- flextable(dat)
ft <- theme_vader(ft)
ft
```
\pagebreak
## Blah
```{r}
ft <- border_outer(ft, border = fp_border_default(width = 2.5, color = "red"))
ft <- border_inner_v(ft, border = fp_border_default(width = 1, color = "cyan"))
ft <- border_inner_h(ft, border = fp_border_default(width = 1, color = "orange"))
ft <- merge_v(ft, j = 1:2)
ft <- merge_h(ft)
ft <- fix_border_issues(ft)
ft
```
## Blah
```{r}
dt <- data.frame(
stringsAsFactors = FALSE,
V1 = c("OOOOOOOO", "OOOOOOOO", "OOOOOOOO"),
V2 = c("XXX", "XXX", "YYY"),
V3 = c("ZZZ", "ZZZ", "ZZZ"),
V4 = c("XXXX XXXX XXXX XXXX",
"XXXX XXXX XXXX XXXX",
"XXXX XXXX XXXX XXXX")
)
dt |>
flextable() |>
set_table_properties(
layout = "autofit", width = .8,
opts_pdf = list(tabcolsep = 3)
) |>
merge_v(j = ~ V1 + V2) |>
valign(valign = "top", part = "all") |>
border_inner_h(part = "all") |>
border_inner_v(part = "all") |>
border_outer(part = "all", border = fp_border_default(color = "red")) |>
autofit() |>
fix_border_issues(part = "all")
```
## blouh
```{r echo=FALSE}
ft <- as_flextable(cars)
ft <- theme_zebra(ft)
ft <- hline(ft, j = 2, part = "body")
ft
```
## kable
```{r}
kable(head(iris))
```
flextable/tests/testthat/rmd/bookdown.Rmd 0000644 0001762 0000144 00000002517 14311145233 020274 0 ustar ligges users ---
title: "bookdown examples"
---
```{r setup, include=FALSE}
set.seed(2)
knitr::opts_chunk$set(echo = FALSE, ft.shadow = FALSE, ft.latex.float = 'float')
library(officer)
library(flextable)
set_flextable_defaults(
font.family = "Arial",
fonts_ignore = TRUE,
font.size = 10,
font.color = "#222222", border.color = "#222222")
str1 <- "Lorem ipsum dolor sit amet, ac id condimentum cras urna velit, "
str2 <- "fringilla nec nostra in. "
str3 <- "Iaculis sit sed in quam cubilia orci dui eget maximus ullamcorper."
fpt1 <- fp_text_default(color = "orange")
fpt2 <- fp_text_default(color = "#068282", italic = TRUE)
fpp1 <- fp_par(
padding.left = 15,
padding.right = 25,
padding.top = 5,
padding.bottom = 10,
text.align = "left")
ft <- qflextable(airquality[sample.int(150, size = 5), ]) |>
set_caption(
fp_p = fpp1,
align_with_table = FALSE,
autonum = run_autonum(seq_id = "tab", bkm = "tbl-flextable", bkm_all = TRUE, prop = fpt1),
caption = as_paragraph(
as_chunk(str1, props = fpt1), str2, as_chunk(str3, props = fpt2)
)
)
```
# some examples
## example 1
```{r}
#| tab.topcaption: false
ft
```
## example 2
```{r}
#| tab.id: tbl-coco
#| tab.cap: Caption zzzz
#| tab.topcaption: true
flextable(cars[1:4, ])
```
## example 3
This is a reference to table: `r run_reference("tbl-flextable")`.
flextable/tests/testthat/rmd/use-printer.Rmd 0000644 0001762 0000144 00000000767 14577133006 020745 0 ustar ligges users ---
title: "use printers"
---
```{r setup, include=FALSE}
library(knitr)
opts_chunk$set(echo = FALSE)
library(flextable)
use_model_printer()
use_df_printer()
```
# a model
```{r}
clotting <- data.frame(
u = c(5,10,15,20,30,40,60,80,100),
lot1 = c(118,58,42,35,27,25,21,19,18),
lot2 = c(69,35,26,21,18,16,13,12,12))
model <- glm(lot1 ~ log(u), data = clotting, family = Gamma)
model
```
# no stars
```{r}
options(show.signif.stars = FALSE)
model
```
## example 2
```{r}
airquality
```
flextable/tests/testthat/test-latex.R 0000644 0001762 0000144 00000002130 14615445131 017437 0 ustar ligges users test_that("white spaces are protected", {
ft <- flextable(data.frame(x = ""))
ft <- delete_part(ft, part = "header")
ft <- mk_par(ft, 1, 1, as_paragraph("foo", " ", "bar"))
str <- flextable:::gen_raw_latex(ft)
expect_true(grepl("{\\ }", str, fixed = TRUE))
})
test_that("fonts are defined in latex", {
gdtools::register_liberationsans()
ft <- flextable::flextable(head(cars, n = 1)) |>
flextable::font(fontname = "Liberation Sans", part = "body")
# R Markdown with pdflatex
knitr::opts_knit$set("quarto.version" = NULL)
latex_str <- flextable:::gen_raw_latex(ft, quarto = FALSE)
expect_no_match(latex_str, regexp = "Liberation Sans", fixed = TRUE)
knitr::opts_knit$set("rmarkdown.pandoc.args" = c("--pdf-engine", "xelatex"))
latex_str <- flextable:::gen_raw_latex(ft, quarto = FALSE)
expect_match(latex_str, regexp = "Liberation Sans", fixed = TRUE)
knitr::opts_knit$set("rmarkdown.pandoc.args" = NULL)
# quarto
flextable:::fake_quarto()
latex_str <- flextable:::gen_raw_latex(ft, quarto = TRUE)
expect_match(latex_str, regexp = "Liberation Sans", fixed = TRUE)
})
flextable/tests/testthat/test-footers.R 0000644 0001762 0000144 00000003017 14615445137 020016 0 ustar ligges users test_that("add_footer", {
data_ref <- structure(
list(
Sepal.Length = c("Sepal", "s", "(cm)"),
Sepal.Width = c("Sepal", "", "(cm)"),
Petal.Length = c("Petal", "", "(cm)"),
Petal.Width = c("Petal", "", "(cm)"),
Species = c("Species", "", "(cm)")
),
.Names = c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width", "Species"),
row.names = c(NA, -3L), class = "data.frame"
)
ft <- flextable(iris[1:6, ])
ft <- add_footer(
ft,
Sepal.Length = "Sepal",
Sepal.Width = "Sepal", Petal.Length = "Petal",
Petal.Width = "Petal", Species = "Species"
)
ft <- add_footer(ft, Sepal.Length = "s", top = FALSE)
ft <- add_footer(
ft,
Sepal.Length = "(cm)",
Sepal.Width = "(cm)", Petal.Length = "(cm)",
Petal.Width = "(cm)", Species = "(cm)", top = FALSE
)
has_ <- flextable:::fortify_content(
ft$footer$content,
default_chunk_fmt = ft$footer$styles$text
)$txt
expect_equal(has_, as.character(unlist(data_ref)))
ft <- flextable(iris[1:6, ])
ft <- add_footer_row(
ft,
values = c("Sepal", "Petal", "Species"),
colwidths = c(2, 2, 1)
)
ft <- add_footer_lines(ft, "s", top = FALSE)
ft <- add_footer_row(ft, values = "(cm)", colwidths = 5, top = FALSE)
has_ <- flextable:::fortify_content(
ft$footer$content,
default_chunk_fmt = ft$footer$styles$text
)$txt
ref <- c(
"Sepal", "s", "(cm)", "Sepal", "s", "(cm)", "Petal", "s", "(cm)",
"Petal", "s", "(cm)", "Species", "s", "(cm)"
)
expect_equal(has_, ref)
})
flextable/tests/testthat/test-headers.R 0000644 0001762 0000144 00000007731 14615445134 017754 0 ustar ligges users test_that("set_header_labels", {
col_keys <- c(
"Species",
"sep1", "Sepal.Length", "Sepal.Width",
"sep2", "Petal.Length", "Petal.Width"
)
ft <- flextable(head(iris), col_keys = col_keys)
ft <- set_header_labels(ft,
Sepal.Length = "Sepal length",
Sepal.Width = "Sepal width", Petal.Length = "Petal length",
Petal.Width = "Petal width"
)
docx_file <- tempfile(fileext = ".docx")
doc <- read_docx()
doc <- body_add_flextable(doc, value = ft)
doc <- print(doc, target = docx_file)
main_folder <- file.path(getwd(), "docx_folder")
unpack_folder(file = docx_file, folder = main_folder)
doc_file <- file.path(main_folder, "/word/document.xml")
doc <- read_xml(doc_file)
colnodes <- xml_find_all(doc, "w:body/w:tbl/w:tr[w:trPr/w:tblHeader]/w:tc")
expect_equal(
xml_text(colnodes),
c("Species", "", "Sepal length", "Sepal width", "", "Petal length", "Petal width")
)
unlink(main_folder, recursive = TRUE, force = TRUE)
ft <- flextable(mtcars)
ft <- set_header_labels(ft, values = letters[1:ncol(mtcars)])
ft <- delete_part(ft, part = "body")
expect_equal(
information_data_chunk(ft)$txt,
letters[1:ncol(mtcars)]
)
})
test_that("add_header", {
data_ref <- structure(
list(
Sepal.Length = c("Sepal", "s", "(cm)"),
Sepal.Width = c("Sepal", "", "(cm)"),
Petal.Length = c("Petal", "", "(cm)"),
Petal.Width = c("Petal", "", "(cm)"),
Species = c("Species", "", "(cm)")
),
.Names = c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width", "Species"),
row.names = c(NA, -3L), class = "data.frame"
)
ft <- flextable(iris[1:6, ])
ft <- set_header_labels(
ft,
Sepal.Length = "Sepal",
Sepal.Width = "Sepal", Petal.Length = "Petal",
Petal.Width = "Petal", Species = "Species"
)
ft <- add_header(ft, Sepal.Length = "s", top = FALSE)
ft <- add_header(
ft,
Sepal.Length = "(cm)",
Sepal.Width = "(cm)", Petal.Length = "(cm)",
Petal.Width = "(cm)", Species = "(cm)", top = FALSE
)
has_ <- flextable:::fortify_content(
ft$header$content,
default_chunk_fmt = ft$header$styles$text
)$txt
expect_equal(has_, as.character(unlist(data_ref)))
ft <- flextable(iris[1:6, ])
ft <- set_header_labels(
ft,
Sepal.Length = "Sepal",
Sepal.Width = "Sepal", Petal.Length = "Petal",
Petal.Width = "Petal", Species = "Species"
)
ft <- add_header(ft, Sepal.Length = "s", top = FALSE)
ft <- add_header(
ft,
Sepal.Length = "(cm)",
Sepal.Width = "(cm)", Petal.Length = "(cm)",
Petal.Width = "(cm)", Species = "(cm)", top = FALSE
)
has_ <- flextable:::fortify_content(
ft$header$content,
default_chunk_fmt = ft$header$styles$text
)$txt
expect_equal(has_, as.character(unlist(data_ref)))
})
test_that("set_header_df", {
typology <- data.frame(
col_keys = c(
"Sepal.Length", "Sepal.Width", "Petal.Length",
"Petal.Width", "Species"
),
what = c("Sepal", "Sepal", "Petal", "Petal", "Species"),
measure = c("Length", "Width", "Length", "Width", "Species"),
stringsAsFactors = FALSE
)
data <- iris[c(1:3, 51:53, 101:104), ]
ft <- flextable(
data,
col_keys = c(
"Species",
"sep_1", "Sepal.Length", "Sepal.Width",
"sep_2", "Petal.Length", "Petal.Width"
)
)
ft <- set_header_df(ft, mapping = typology, key = "col_keys")
data_ref <- structure(
list(
Species = c("Species", "Species"),
sep_1 = c("", ""),
Sepal.Length = c("Sepal", "Length"),
Sepal.Width = c("Sepal", "Width"),
sep_2 = c("", ""),
Petal.Length = c("Petal", "Length"),
Petal.Width = c("Petal", "Width")
),
.Names = c("Species", "sep_1", "Sepal.Length", "Sepal.Width", "sep_2", "Petal.Length", "Petal.Width"),
row.names = c(NA, -2L), class = "data.frame"
)
expect_ <- as.character(unlist(data_ref))
has_ <- flextable:::fortify_content(
ft$header$content,
default_chunk_fmt = ft$header$styles$text
)$txt
expect_equal(has_, expect_)
})
flextable/tests/testthat/test-gen_grob.R 0000644 0001762 0000144 00000011164 14615445135 020117 0 ustar ligges users gdtools::register_liberationsans()
init_flextable_defaults()
set_flextable_defaults(
font.family = "Liberation Sans",
border.color = "#333333")
test_that("png is created", {
ft <- as_flextable(iris)
file <- tempfile(fileext = ".png")
try(invisible(save_as_image(x = ft, path = file, res = 150)),
silent = TRUE)
expect_true(file.exists(file))
expect_gt(file.info(file)$size, 20000)
})
test_that("merged borders", {
local_edition(3)
dat <- data.frame(a = c(1, 1, 2, 2, 5), b = 6:10)
ft <- flextable(dat)
ft <- merge_v(ft, ~a, part = "body")
ft <- hline(
x = ft,
i = 2, part = "body",
border = fp_border(color = "red")
)
gr <- gen_grob(ft)
expect_length(gr$children, 10)
expect_equal(gr$children[[3]]$children$borders$children[[1]]$gp$col, "red")
expect_length(gr$children[[1]]$children$borders$children, 2)
expect_equal(gr$children[[1]]$children$borders$children[[1]]$gp$col, "#333333")
expect_equal(gr$children[[1]]$children$borders$children[[1]]$x0, grid::unit(0, "npc"))
expect_equal(gr$children[[1]]$children$borders$children[[1]]$x1, grid::unit(1, "npc"))
expect_equal(gr$children[[1]]$children$borders$children[[1]]$y0, grid::unit(1, "npc"))
expect_equal(gr$children[[1]]$children$borders$children[[1]]$y1, grid::unit(1, "npc"))
expect_equal(gr$children[[1]]$children$borders$children[[2]]$gp$col, "#333333")
expect_equal(gr$children[[1]]$children$borders$children[[2]]$x0, grid::unit(0, "npc"))
expect_equal(gr$children[[1]]$children$borders$children[[2]]$x1, grid::unit(1, "npc"))
expect_equal(gr$children[[1]]$children$borders$children[[2]]$y0, grid::unit(0, "npc"))
expect_equal(gr$children[[1]]$children$borders$children[[2]]$y1, grid::unit(0, "npc"))
expect_length(gr$children[[10]]$children$borders$children, 1)
expect_equal(gr$children[[10]]$children$borders$children[[1]]$gp$col, "#333333")
expect_equal(gr$children[[10]]$children$borders$children[[1]]$x0, grid::unit(0, "npc"))
expect_equal(gr$children[[10]]$children$borders$children[[1]]$x1, grid::unit(1, "npc"))
expect_equal(gr$children[[10]]$children$borders$children[[1]]$y0, grid::unit(0, "npc"))
expect_equal(gr$children[[10]]$children$borders$children[[1]]$y1, grid::unit(0, "npc"))
})
test_that("text wrapping", {
text <- "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
source1 <- "DATA_SOURCE_A.COURSE_TITLE\nDATA_SOURCE_A.SUBJECT_DESCR\nDATA_SOURCE_A.CATALOG_NUMBER"
source2 <- "DATA_SOURCE_A.GRADING_BASIS\nDATA_SOURCE_A.OFFICIAL_GRADE\nDATA_SOURCE_B.STUDENT_GROUP"
temp_dat <- data.frame(
label = c("Sources", "", "Notes"),
col1 = c(source1, "", text),
col2 = c(source2, "", text)
)
# Create table
ft <- flextable(temp_dat)
ft <- merge_h(ft, part = "body")
gr <- gen_grob(ft, fit = "fixed")
expect_length(gr$children, 9)
expect_equal(gr$children[[5]]$children$contents$ftgrobs[[1]]$label, source1)
expect_equal(gr$children[[6]]$children$contents$ftgrobs[[1]]$label, source2)
# check wrap on 3 rows
expect_length(gr$children[[5]]$children$contents$children, 3)
expect_length(gr$children[[6]]$children$contents$children, 3)
expect_equal(gr$children[[8]]$children$contents$ftgrobs[[1]]$label, "Notes")
expect_length(gr$children[[8]]$children$contents$children, 1)
expect_equal(gr$children[[9]]$children$contents$ftgrobs[[1]]$label, text)
# check wrap on 3 rows
expect_length(gr$children[[9]]$children$contents$children, 3)
# check that height and width are greater than those of smaller cells
expect_gt(gr$children$cell_2_2$children$contents$ftpar$height,
gr$children$cell_1_2$children$contents$ftpar$height
)
expect_gt(gr$children$cell_2_2$children$contents$ftpar$width,
gr$children$cell_2_1$children$contents$ftpar$width
)
})
test_that("grid with raster", {
skip_if_not_installed("magick")
img.file <- file.path(
R.home("doc"),
"html", "logo.jpg"
)
myft <- flextable(head(iris))
myft <- prepend_chunks(
x = myft,
i = 1:2, j = 1,
as_image(src = img.file),
part = "body"
)
ft <- autofit(myft)
gr <- gen_grob(ft)
expect_s3_class(gr$children[[6]]$children$contents$ftgrobs[[1]], "rastergrob")
expect_s3_class(gr$children[[6]]$children$contents$ftgrobs[[2]], "text")
expect_s3_class(gr$children[[11]]$children$contents$ftgrobs[[1]], "rastergrob")
expect_s3_class(gr$children[[11]]$children$contents$ftgrobs[[2]], "text")
expect_s3_class(gr$children[[12]]$children$contents$ftgrobs[[1]], "text")
})
flextable/tests/testthat/test-errors.R 0000644 0001762 0000144 00000003406 14615445140 017645 0 ustar ligges users test_that("rows selections", {
dummy_df <- data.frame(
my_col = rep(letters[1:3], each = 2),
row.names = letters[21:26],
stringsAsFactors = FALSE
)
ft <- flextable(dummy_df)
expect_error(bold(ft, i = ~ my_col %in% "a", part = "header"))
expect_error(bold(ft, i = 1L:8L), "invalid row selection")
expect_error(bold(ft, i = -9), "invalid row selection")
expect_error(bold(ft, i = rep(TRUE, 10)), "invalid row selection")
expect_error(bold(ft, i = c("m", "n")), "invalid row selection")
})
test_that("columns selections", {
ft <- flextable(iris)
expect_error(bold(ft, j = ~ Sepalsd.Length + Species), "Sepalsd.Length")
expect_error(bold(ft, j = 1:6), "invalid columns selection")
expect_error(bold(ft, j = c("Sepalsd.Length")), "Sepalsd.Length")
})
test_that("part=header and formula selection for rows", {
ft <- flextable(head(mtcars, n = 10))
def_cell <- fp_cell(border = fp_border(color = "#00FFFF"))
def_par <- fp_par(text.align = "center")
expect_error(style(ft, i = ~ mpg < 20, pr_c = def_cell, pr_p = def_par, part = "all"))
expect_error(bg(ft, i = ~ mpg < 20, bg = "#DDDDDD", part = "header"))
expect_error(bold(ft, i = ~ mpg < 20, bold = TRUE, part = "header"))
expect_error(fontsize(ft, i = ~ mpg < 20, size = 10, part = "header"))
expect_error(italic(ft, i = ~ mpg < 20, italic = TRUE, part = "header"))
expect_error(color(ft, i = ~ mpg < 20, color = "red", part = "header"))
expect_error(padding(ft, i = ~ mpg < 20, padding = 3, part = "header"))
expect_error(align(ft, i = ~ mpg < 20, align = "center", part = "header"))
expect_error(border(ft,
i = ~ mpg < 20, border = fp_border(color = "orange"),
part = "header"
))
expect_error(rotate(ft, i = ~ mpg < 20, rotation = "lrtb", align = "top", part = "header"))
})
flextable/tests/testthat/test-misc.R 0000644 0001762 0000144 00000005460 14615445163 017273 0 ustar ligges users ft <- flextable(iris)
test_that("print as log", {
expect_output(print(ft, preview = "log"), "a flextable object")
expect_output(print(ft, preview = "log"), "header has 1 row")
expect_output(print(ft, preview = "log"), "body has 150 row")
})
test_that("data selectors", {
ft <- flextable(
data = iris,
col_keys = c("ouch", "Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width", "Species", "blop")
)
expect_equal(
flextable:::as_col_keys(ft$body, 2, blanks = ft$blanks),
"Sepal.Width"
)
expect_equal(
flextable:::as_col_keys(ft$body, -5, blanks = ft$blanks),
c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width")
)
expect_equal(
flextable:::as_col_keys(ft$body, c(1, 2), blanks = ft$blanks),
c("Sepal.Length", "Sepal.Width")
)
expect_equal(
flextable:::as_col_keys(ft$body, NULL, blanks = ft$blanks),
colnames(iris)
)
expect_equal(
flextable:::as_col_keys(ft$body, c(TRUE, FALSE, TRUE, FALSE, TRUE),
blanks = ft$blanks
),
c("Sepal.Length", "Petal.Length", "Species")
)
expect_warning(
flextable:::as_col_keys(ft$body, "Julio-Iglesias", blanks = ft$blanks)
)
})
test_that("selection and merge_v", {
ft <- flextable(
data = iris[98:103, ],
col_keys = c("aaa", "Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width")
)
ft <- theme_box(ft)
ft <- merge_v(ft, target = "aaa", j = "Species")
expect_equal(
ft$body$spans$columns[, 1],
c(3L, 0L, 0L, 3L, 0L, 0L)
)
expect_warning(merge_v(ft, target = "aaa", j = "zzz"))
expect_error(merge_v(ft, target = "Species", j = "Sepal.Width"))
})
test_that("selection and colors", {
colourer <- function(z) {
x <- rep("pink", length(z))
x[is.na(z)] <- "#999999"
w_avg <- which(z < mean(z, na.rm = TRUE))
x[w_avg] <- "cyan"
x
}
dat <- iris[98:103, ]
dat[1, 1] <- NA
dat[2, 2] <- NA
dat[3, 3] <- NA
dat[4, 4] <- NA
ft <- flextable(data = dat)
ft <- theme_box(ft)
ft <- bg(ft, j = ~ . - Species, bg = colourer)
expected_values <- c(
"#999999", "cyan", "cyan", "pink", "cyan", "pink",
"cyan", "#999999", "cyan", "pink", "cyan", "pink", "cyan", "cyan",
"#999999", "pink", "pink", "pink", "cyan", "cyan", "cyan", "#999999",
"pink", "pink", "transparent", "transparent", "transparent",
"transparent", "transparent", "transparent"
)
bg_values <- as.vector(ft$body$styles$cells$background.color$data)
expect_equal(bg_values, expected_values)
ft <- bg(ft,
source = "Species", j = "Sepal.Length",
bg = function(z) {
x <- rep("red", length(z))
x[is.na(z)] <- "#999999"
w_ver <- which(z %in% "versicolor")
x[w_ver] <- "blue"
x
}
)
bg_values <- as.vector(ft$body$styles$cells$background.color$data[, 1])
expect_equal(bg_values, rep(c("blue", "red"), each = 3))
})
flextable/tests/testthat/test-df_printer.R 0000644 0001762 0000144 00000002442 14707417314 020470 0 ustar ligges users test_that("use_model_printer and use_df_printer works", {
skip_if_not(rmarkdown::pandoc_available("1.12.3"))
rmd_file <- tempfile(fileext = ".Rmd")
file.copy("rmd/use-printer.Rmd", rmd_file)
outfile <- tempfile(fileext = ".html")
options(show.signif.stars = TRUE)
rmarkdown::render(rmd_file,
output_file = outfile, output_format = "html_document",
envir = new.env(), quiet = TRUE
)
doc <- read_html(outfile)
table_nodes <- xml_find_all(doc, "body//*/table")
testthat::expect_length(table_nodes, n = 3)
# check last table that should be a summary table
table_node_3 <- table_nodes[[3]]
expect_length(xml_children(xml_child(table_node_3, search = "/thead")), 2)
expect_length(xml_children(xml_child(table_node_3, search = "/tbody")), 10)
tfoot_content <- xml_child(table_node_3, search = "/tfoot")
expect_length(xml_children(tfoot_content), 1)
expect_equal(xml_text(tfoot_content), "n: 153")
# check first table and last column should have stars
first_tr <- xml_find_first(doc, "//table/tbody/tr")
expect_length(xml_children(first_tr), 6)
expect_equal(xml_text(xml_child(first_tr, 6)), "***")
# check second table has 5 columns
first_tr <- xml_find_first(doc, "//*[@id='no-stars']//table/tbody/tr")
expect_length(xml_children(first_tr), 5)
})
flextable/tests/testthat/test-borders.R 0000644 0001762 0000144 00000010467 14615445127 020003 0 ustar ligges users init_flextable_defaults()
snap_folder_test_file <- "borders"
defer_cleaning_snapshot_directory(snap_folder_test_file)
set.seed(2)
USUBJID <- sprintf("01-ABC-%04.0f", 1:200)
VISITS <- c("SCREENING 1", "WEEK 2", "MONTH 3")
LBTEST <- c("Albumin", "Sodium")
VISITNUM <- seq_along(VISITS)
LBBLFL <- rep(NA_character_, length(VISITNUM))
LBBLFL[1] <- "Y"
VISIT <- data.frame(VISIT = VISITS, VISITNUM = VISITNUM, LBBLFL = LBBLFL, stringsAsFactors = FALSE)
labdata <- expand.grid(USUBJID = USUBJID, LBTEST = LBTEST, VISITNUM = VISITNUM, stringsAsFactors = FALSE)
setDT(labdata)
labdata <- merge(labdata, VISIT, by = "VISITNUM")
labdata[, c("LBNRIND") := list(sample(x = c("LOW", "NORMAL", "HIGH"), size = .N, replace = TRUE, prob = c(.03, .9, .07)))]
setDF(labdata)
SHIFT_TABLE <- shift_table(
x = labdata, cn_visit = "VISIT", cn_grade = "LBNRIND", cn_usubjid = "USUBJID",
cn_lab_cat = "LBTEST", cn_is_baseline = "LBBLFL", baseline_identifier = "Y", grade_levels = c("LOW", "NORMAL", "HIGH")
)
SHIFT_TABLE_VISIT <- attr(SHIFT_TABLE, "VISIT_N")
SHIFT_TABLE$VISIT <- attr(SHIFT_TABLE, "FUN_VISIT")(SHIFT_TABLE$VISIT)
SHIFT_TABLE$BASELINE <- attr(SHIFT_TABLE, "FUN_GRADE")(SHIFT_TABLE$BASELINE)
SHIFT_TABLE$LBNRIND <- attr(SHIFT_TABLE, "FUN_GRADE")(SHIFT_TABLE$LBNRIND)
SHIFT_TABLE_VISIT$VISIT <- attr(SHIFT_TABLE, "FUN_VISIT")(SHIFT_TABLE_VISIT$VISIT)
tab <- tabulator(
x = SHIFT_TABLE,
hidden_data = SHIFT_TABLE_VISIT,
row_compose = list(
VISIT = as_paragraph(VISIT, "\n(N=", N_VISIT, ")")
),
rows = c("LBTEST", "VISIT", "BASELINE"), columns = c("LBNRIND"),
`n` = as_paragraph(N),
`%` = as_paragraph(as_chunk(PCT, formatter = function(z) {
formatC(z * 100, digits = 1, format = "f", flag = "0", width = 4)
}))
)
ft_1 <- as_flextable(
x = tab, separate_with = "VISIT",
label_rows = c(
LBTEST = "Lab Test",
VISIT = "Visit",
BASELINE = "Reference\nRange\nIndicator"
)
)
ft_1 <- width(ft_1, j = 3, width = 1)
test_that("pptx, docx, and html borders", {
skip_if_not_local_testing(check_html = TRUE)
# pptx borders
handle_manual_snapshots(snap_folder_test_file, "pptx-borders")
doconv::expect_snapshot_doc(
x = save_as_pptx(ft_1, path = tempfile(fileext = ".pptx")),
name = "pptx-borders", engine = "testthat"
)
# docx borders
handle_manual_snapshots(snap_folder_test_file, "docx-borders")
doconv::expect_snapshot_doc(
x = save_as_docx(ft_1, path = tempfile(fileext = ".docx")),
name = "docx-borders", engine = "testthat"
)
# html borders
handle_manual_snapshots(snap_folder_test_file, "html-borders")
path <- save_as_html(ft_1, path = tempfile(fileext = ".html"))
skip_if_not_installed("chromote")
suppressMessages(is_there_chrome <- chromote::find_chrome())
skip_if(is.null(is_there_chrome))
doconv::expect_snapshot_html(name = "html-borders", path, engine = "testthat")
})
rmd_file_0 <- "rmd/borders.Rmd"
if (!file.exists(rmd_file_0)) { # just for dev purpose
rmd_file_0 <- "tests/testthat/rmd/borders.Rmd"
}
rmd_file <- tempfile(fileext = ".Rmd")
file.copy(rmd_file_0, rmd_file, overwrite = TRUE)
html_file <- gsub("\\.Rmd$", ".html", rmd_file)
docx_file <- gsub("\\.Rmd$", ".docx", rmd_file)
pdf_file <- gsub("\\.Rmd$", ".pdf", rmd_file)
pptx_file <- gsub("\\.Rmd$", ".pptx", rmd_file)
test_that("pdf and office complex borders", {
skip_if_not_local_testing(min_pandoc_version = "2.7.3")
# pdf office complex borders
render(rmd_file,
output_format = rmarkdown::pdf_document(latex_engine = "xelatex"),
output_file = pdf_file,
envir = new.env(),
quiet = TRUE
)
handle_manual_snapshots(snap_folder_test_file, "pdf-complex-borders")
doconv::expect_snapshot_doc(name = "pdf-complex-borders", pdf_file, engine = "testthat")
# office complex borders
render(rmd_file,
output_format = "word_document",
output_file = docx_file,
envir = new.env(),
quiet = TRUE
)
handle_manual_snapshots(snap_folder_test_file, "docx-complex-borders")
doconv::expect_snapshot_doc(name = "docx-complex-borders", docx_file, engine = "testthat")
render(rmd_file,
output_format = "powerpoint_presentation",
output_file = pptx_file,
envir = new.env(),
quiet = TRUE
)
handle_manual_snapshots(snap_folder_test_file, "pptx-complex-borders")
doconv::expect_snapshot_doc(name = "pptx-complex-borders", pptx_file, engine = "testthat")
})
init_flextable_defaults()
flextable/tests/testthat/test-as_flextable.R 0000644 0001762 0000144 00000042312 14707415535 020770 0 ustar ligges users test_that("data.frame", {
dummy_df <- data.frame(
A = rep(letters[1:3], each = 2),
B = seq(0, 1, length = 6)
)
ft <- as_flextable(dummy_df)
expect_equal(
information_data_chunk(ft)$txt,
c(
"A", "B", "character", "numeric", "a", "0.0", "a", "0.2",
"b", "0.4", "b", "0.6", "c", "0.8", "c", "1.0", "n: 6", "n: 6"
)
)
ft <- as_flextable(dummy_df[1, ])
expect_equal(
information_data_chunk(ft)$txt,
c("A", "
", "character", "a", "B", "
", "numeric", "0")
)
})
test_that("grouped_data", {
my_CO2 <- CO2
setDT(my_CO2)
my_CO2$conc <- as.integer(my_CO2$conc)
data_co2 <- dcast(my_CO2, Treatment + conc ~ Type,
value.var = "uptake", fun.aggregate = mean
)
expect_silent(
data_co2 <- as_grouped_data(x = data_co2, groups = c("Treatment"))
)
expect_equal(
data_co2$Treatment[seq_len(2)],
factor(c("nonchilled", NA), levels = c("nonchilled", "chilled"))
)
expect_equal(
data_co2$Treatment[c(8, 9, 10)],
factor(c(NA, "chilled", NA), levels = c("nonchilled", "chilled"))
)
out_tmp <- data_co2[1, , drop = TRUE]
expect_equal(attr(out_tmp, "groups"), "Treatment")
expect_equal(attr(out_tmp, "columns"), c("conc", "Quebec", "Mississippi"))
expect_equal(unlist(out_tmp, use.names = FALSE), c(1, NA, NA, NA))
expect_s3_class(data_co2, "grouped_data")
expect_silent(
data_co2 <- as_grouped_data(x = data_co2, groups = c("Treatment"), expand_single = TRUE)
)
expect_true(all(is.na(unlist(data_co2[c(12, 13), , drop = TRUE], use.names = FALSE))))
ft <- as_flextable(data_co2)
expect_equal(
information_data_chunk(ft)$txt[seq_len(9)],
c("conc", "Quebec", "Mississippi", "Treatment", ": ", "nonchilled", "", "", "")
)
expect_equal(information_data_chunk(ft)$txt[15], "95")
ft <- as_flextable(data_co2, hide_grouplabel = TRUE)
expect_equal(
information_data_chunk(ft)$txt[seq_len(9)],
c("conc", "Quebec", "Mississippi", "nonchilled", "", "", "", "", "")
)
})
test_that("glm and lm", {
skip_if_not_installed("broom")
options("show.signif.stars" = TRUE)
dat <- attitude
dat$high.rating <- (dat$rating > 70)
probit.model <- glm(high.rating ~ learning + critical +
advance, data = dat, family = binomial(link = "probit"))
expect_silent(ft <- as_flextable(probit.model))
expect_equal(
information_data_chunk(ft)$txt[5],
"Pr(>|z|)"
)
expect_equal(
information_data_chunk(ft)$txt[31],
"Signif. codes: 0 <= '***' < 0.001 < '**' < 0.01 < '*' < 0.05"
)
lmod <- lm(rating ~ complaints + privileges +
learning + raises + critical, data = attitude)
ft <- as_flextable(lmod)
expect_equal(
information_data_chunk(ft)$txt[5],
"Pr(>|t|)"
)
expect_equal(
information_data_chunk(ft)$txt[44],
"Signif. codes: 0 <= '***' < 0.001 < '**' < 0.01 < '*' < 0.05"
)
expect_equal(
information_data_chunk(ft)$txt[72],
"F-statistic: 12.06 on 24 and 5 DF, p-value: 0.0000"
)
})
test_that("htest", {
set.seed(16)
M <- as.table(rbind(c(762, 327, 468), c(484, 239, 477)))
dimnames(M) <- list(
gender = c("F", "M"),
party = c("Democrat", "Independent", "Republican")
)
ft <- as_flextable(stats::chisq.test(M))
expect_equal(
information_data_chunk(ft)$txt[6],
"0.0000"
)
})
test_that("continuous_summary works", {
ft_1 <- continuous_summary(iris, names(iris)[1:4],
by = "Species",
hide_grouplabel = FALSE
)
expect_identical(
information_data_chunk(ft_1)$txt[c(1, 11, 14, 71)],
c("Species", "# na", "Sepal.Length", "setosa")
)
})
test_that("transformation of mixed models works", {
skip_if_not_installed("broom.mixed")
skip_if_not_installed("nlme")
m1 <- nlme::lme(distance ~ age, data = nlme::Orthodont)
ft <- as_flextable(m1)
expect_equal(
information_data_chunk(ft)$txt[c(18, 108)],
c("(Intercept)", "Akaike Information Criterion: 454.6")
)
})
test_that("kmeans works", {
set.seed(11)
cl <- kmeans(scale(mtcars[1:7]), 5)
ft <- as_flextable(cl)
expect_equal(
information_data_chunk(ft)$txt[c(37, 163)],
c("1.0906", "BSS/TSS ratio: 80.1%")
)
})
test_that("partitioning around medoids works", {
skip_if_not_installed("cluster")
set.seed(11)
dat <- as.data.frame(scale(mtcars[1:7]))
cl <- cluster::pam(dat, 3)
ft <- as_flextable(cl)
expect_equal(
information_data_chunk(ft)$txt[c(37, 163, 17)],
c("", NA, "2.2")
)
})
test_that("grouped data structure", {
init_flextable_defaults()
set_flextable_defaults(
post_process_pptx = function(x) {
set_table_properties(x, layout = "fixed") |>
autofit()
}
)
data_co2 <-
structure(
list(
Treatment = structure(c(3L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 4L, 4L),
levels = c("nonchilled", "chilled", "zoubi", "bisou"), class = "factor"
),
conc = c(85L, 95L, 175L, 250L, 350L, 500L, 675L, 1000L, 95L, 175L, 250L, 350L, 500L, 675L, 1000L, NA, 1000L),
Quebec = c(
12, 15.2666666666667, 30.0333333333333, 37.4, 40.3666666666667, 39.6, 41.5, 43.1666666666667,
12.8666666666667, 24.1333333333333, 34.4666666666667, 35.8, 36.6666666666667,
37.5, 40.8333333333333, 43, 43
),
Mississippi = c(
10, 11.3, 20.2, 27.5333333333333, 29.9, 30.6, 30.5333333333333, 31.6, 9.6, 14.7666666666667, 16.1,
16.6, 16.6333333333333, 18.2666666666667, 18.7333333333333, 19, 19
)
),
row.names = c(NA, -17L),
class = "data.frame"
)
gdata <- as_grouped_data(x = data_co2, groups = c("Treatment"))
ft_1 <- as_flextable(gdata)
ft_1 <- colformat_double(ft_1, digits = 2)
ft_1 <- set_table_properties(ft_1, layout = "autofit")
# pptx testing
pptx_file <- tempfile(fileext = ".pptx")
save_as_pptx(ft_1, path = pptx_file)
doc <- read_pptx(pptx_file)
xml_body <- doc$slide$get_slide(1)$get()
xml_tbl <- xml_find_first(xml_body, "/p:sld/p:cSld/p:spTree/p:graphicFrame/a:graphic/a:graphicData/a:tbl")
xml_cell_2_1 <- xml_child(xml_tbl, "a:tr[2]/a:tc[1]")
expect_equal(xml_text(xml_cell_2_1), "Treatment: zoubi")
expect_equal(xml_attr(xml_cell_2_1, "gridSpan"), "3")
xml_cell_2_2 <- xml_child(xml_tbl, "a:tr[2]/a:tc[2]")
expect_equal(xml_text(xml_cell_2_2), "")
expect_equal(xml_attr(xml_cell_2_2, "hMerge"), "true")
xml_cell_2_3 <- xml_child(xml_tbl, "a:tr[2]/a:tc[3]")
expect_equal(xml_text(xml_cell_2_3), "")
expect_equal(xml_attr(xml_cell_2_3, "hMerge"), "true")
xml_cell_3_1 <- xml_child(xml_tbl, "a:tr[3]/a:tc[1]")
expect_equal(xml_text(xml_cell_3_1), "85")
xml_cell_3_2 <- xml_child(xml_tbl, "a:tr[3]/a:tc[2]")
expect_equal(xml_text(xml_cell_3_2), "12.00")
xml_cell_3_3 <- xml_child(xml_tbl, "a:tr[3]/a:tc[3]")
expect_equal(xml_text(xml_cell_3_3), "10.00")
expect_equal(xml_attr(xml_child(xml_tbl, "a:tr[1]/a:tc[1]/a:tcPr/a:lnL"), "w"), "0")
expect_equal(xml_attr(xml_child(xml_tbl, "a:tr[1]/a:tc[1]/a:tcPr/a:lnR"), "w"), "0")
expect_equal(xml_attr(xml_child(xml_tbl, "a:tr[1]/a:tc[1]/a:tcPr/a:lnB"), "w"), "19050")
expect_equal(xml_attr(xml_child(xml_tbl, "a:tr[1]/a:tc[1]/a:tcPr/a:lnT"), "w"), "19050")
expect_equal(xml_attr(xml_child(xml_tbl, "a:tr[1]/a:tc[2]/a:tcPr/a:lnL"), "w"), "0")
expect_equal(xml_attr(xml_child(xml_tbl, "a:tr[1]/a:tc[2]/a:tcPr/a:lnR"), "w"), "0")
expect_equal(xml_attr(xml_child(xml_tbl, "a:tr[1]/a:tc[2]/a:tcPr/a:lnB"), "w"), "19050")
expect_equal(xml_attr(xml_child(xml_tbl, "a:tr[1]/a:tc[2]/a:tcPr/a:lnT"), "w"), "19050")
expect_equal(xml_attr(xml_child(xml_tbl, "a:tr[1]/a:tc[3]/a:tcPr/a:lnL"), "w"), "0")
expect_equal(xml_attr(xml_child(xml_tbl, "a:tr[1]/a:tc[3]/a:tcPr/a:lnR"), "w"), "0")
expect_equal(xml_attr(xml_child(xml_tbl, "a:tr[1]/a:tc[3]/a:tcPr/a:lnB"), "w"), "19050")
expect_equal(xml_attr(xml_child(xml_tbl, "a:tr[1]/a:tc[3]/a:tcPr/a:lnT"), "w"), "19050")
expect_equal(xml_attr(xml_child(xml_tbl, "a:tr[2]/a:tc[1]/a:tcPr/a:lnL"), "w"), "0")
expect_equal(xml_attr(xml_child(xml_tbl, "a:tr[2]/a:tc[1]/a:tcPr/a:lnR"), "w"), "0")
expect_equal(xml_attr(xml_child(xml_tbl, "a:tr[2]/a:tc[1]/a:tcPr/a:lnB"), "w"), "0")
expect_equal(xml_attr(xml_child(xml_tbl, "a:tr[2]/a:tc[1]/a:tcPr/a:lnT"), "w"), "0")
expect_equal(xml_attr(xml_child(xml_tbl, "a:tr[22]/a:tc[1]/a:tcPr/a:lnL"), "w"), "0")
expect_equal(xml_attr(xml_child(xml_tbl, "a:tr[22]/a:tc[1]/a:tcPr/a:lnR"), "w"), "0")
expect_equal(xml_attr(xml_child(xml_tbl, "a:tr[22]/a:tc[1]/a:tcPr/a:lnB"), "w"), "19050")
expect_equal(xml_attr(xml_child(xml_tbl, "a:tr[22]/a:tc[1]/a:tcPr/a:lnT"), "w"), "0")
# docx testing
docx_file <- tempfile(fileext = ".docx")
save_as_docx(ft_1, path = docx_file)
doc <- read_docx(docx_file)
xml_doc <- docx_body_xml(doc)
xml_tbl <- xml_find_first(xml_doc, "/w:document/w:body/w:tbl")
xml_cell_2_1 <- xml_child(xml_tbl, "w:tr[2]/w:tc[1]")
expect_equal(xml_text(xml_cell_2_1), "Treatment: zoubi")
expect_equal(xml_attr(xml_child(xml_cell_2_1, "w:tcPr/w:gridSpan"), "val"), "3")
xml_cell_2_2 <- xml_child(xml_tbl, "w:tr[2]/w:tc[2]")
expect_s3_class(xml_cell_2_2, "xml_missing")
xml_cell_1_1 <- xml_child(xml_tbl, "w:tr[1]/w:tc[1]")
expect_equal(xml_text(xml_cell_1_1), "conc")
xml_cell_1_2 <- xml_child(xml_tbl, "w:tr[1]/w:tc[2]")
expect_equal(xml_text(xml_cell_1_2), "Quebec")
xml_cell_1_3 <- xml_child(xml_tbl, "w:tr[1]/w:tc[3]")
expect_equal(xml_text(xml_cell_1_3), "Mississippi")
expect_equal(xml_attr(xml_child(xml_cell_1_3, "w:tcPr/w:tcBorders/w:bottom"), "sz"), "12")
expect_equal(xml_attr(xml_child(xml_cell_1_3, "w:tcPr/w:tcBorders/w:top"), "sz"), "12")
expect_equal(xml_attr(xml_child(xml_cell_1_3, "w:tcPr/w:tcBorders/w:left"), "sz"), "0")
expect_equal(xml_attr(xml_child(xml_cell_1_3, "w:tcPr/w:tcBorders/w:right"), "sz"), "0")
expect_equal(xml_attr(xml_child(xml_cell_2_1, "w:tcPr/w:tcBorders/w:bottom"), "sz"), "0")
expect_equal(xml_attr(xml_child(xml_cell_2_1, "w:tcPr/w:tcBorders/w:top"), "sz"), "12")
expect_equal(xml_attr(xml_child(xml_cell_2_1, "w:tcPr/w:tcBorders/w:left"), "sz"), "0")
expect_equal(xml_attr(xml_child(xml_cell_2_1, "w:tcPr/w:tcBorders/w:right"), "sz"), "0")
# html testing
html_file <- tempfile(fileext = ".html")
save_as_html(ft_1, path = html_file)
xml_doc <- read_html(html_file)
xml_tbl <- xml_find_first(xml_doc, "//table")
xml_cell_2_1 <- xml_child(xml_tbl, "tbody/tr[1]/td[1]")
expect_equal(xml_text(xml_cell_2_1), "Treatment: zoubi")
expect_equal(xml_attr(xml_cell_2_1, "colspan"), "3")
xml_cell_2_2 <- xml_child(xml_tbl, "tbody/tr[1]/td[2]")
expect_s3_class(xml_cell_2_2, "xml_missing")
xml_cell_1_1 <- xml_child(xml_tbl, "thead/tr[1]/th[1]")
expect_equal(xml_text(xml_cell_1_1), "conc")
xml_cell_1_2 <- xml_child(xml_tbl, "thead/tr[1]/th[2]")
expect_equal(xml_text(xml_cell_1_2), "Quebec")
xml_cell_1_3 <- xml_child(xml_tbl, "thead/tr[1]/th[3]")
expect_equal(xml_text(xml_cell_1_3), "Mississippi")
init_flextable_defaults()
})
labelled_df <- data.frame(
region =
structure(
c(1, 2, 1, 9, 2, 3),
labels = c(north = 1, south = 2, center = 3, missing = 9),
label = "Region of the respondent"
),
sex =
structure(
c("f", "f", "m", "m", "m", "f"),
labels = c(female = "f", male = "m"),
label = "Sex of the respondent"
),
value = 1:6
)
test_that("labelled data", {
ft <- flextable(labelled_df, use_labels = TRUE)
expected_txt <- c(
"Region of the respondent", "Sex of the respondent", "value",
"north", "female", "1", "south", "female", "2", "north", "male",
"3", "missing", "male", "4", "south", "male", "5", "center", "female",
"6")
expect_equal(
information_data_chunk(ft)$txt,
expected_txt
)
ft <- flextable(labelled_df, use_labels = FALSE)
expected_txt <- c(
"region", "sex", "value", "1", "f", "1", "2", "f", "2", "1",
"m", "3", "9", "m", "4", "2", "m", "5", "3", "f", "6"
)
expect_equal(
information_data_chunk(ft)$txt,
expected_txt
)
expected_txt <- c(
"region", "sex", "sex", "sex", "region", "female", "male",
"Total", "north", "1", "", "1", "", "2", "", "south", "1", "",
"1", "", "2", "", "center", "1", "", "", "", "1", "", "missing",
"", "", "1", "", "1", "", "Total", "3", "", "3", "", "6", ""
)
ft <- proc_freq(
labelled_df, row = "region", col = "sex",
include.row_percent = FALSE,
include.column_percent = FALSE,
include.table_percent = FALSE
)
expect_equal(
information_data_chunk(ft)$txt,
expected_txt
)
expected_txt <- c(
"", "", "", "Statistic", "
", "(N=6)", "Region of the respondent",
"north", "", "2 (33.3%)", "Region of the respondent", "south",
"", "2 (33.3%)", "Region of the respondent", "center", "", "1 (16.7%)",
"Region of the respondent", "Missing", "", "1 (16.7%)", "Sex of the respondent",
"female", "", "3 (50.0%)", "Sex of the respondent", "male", "",
"3 (50.0%)", "value", "Mean (SD)", "", "3.5 (1.9)", "value",
"Median (IQR)", "", "3.5 (2.5)", "value", "Range", "", "1.0 - 6.0"
)
ft <- as_flextable(summarizor(labelled_df))
expect_equal(
information_data_chunk(ft)$txt,
expected_txt
)
})
test_that("package tables", {
skip_if_not_installed("tables")
require("tables", quietly = TRUE)
x <- tabular((Factor(gear, "Gears") + 1) * ((n = 1) + Percent() +
(RowPct = Percent("row")) + (ColPct = Percent("col"))) ~
(Factor(carb, "Carburetors") + 1) * Format(digits = 1),
data = mtcars)
ft <- as_flextable(
x,
spread_first_col = TRUE,
row_title = as_paragraph(
colorize("Gears: ", color = "#666666"),
colorize(as_b(.row_title), color = "red")
)
)
idc <- information_data_chunk(ft)
expected_txt <- c(
"", "Carburetors", "", "", "", "", "", "", "", "1", "2", "3",
"4", "6", "8", "All"
)
expect_equal(
idc[idc$.part %in% "header",]$txt,
expected_txt
)
expected_txt <- c(
"Gears: ", "3", "", "", "", "", "", "", "", "n", "3", "4",
"3", "5", "0", "0", "15", "Percent", "9", "12", "9", "16", "0",
"0", "47", "RowPct", "20", "27", "20", "33", "0", "0", "100",
"ColPct", "43", "40", "100", "50", "0", "0", "47"
)
expect_equal(
idc[idc$.part %in% "body" & idc$.row_id < 6,]$txt,
expected_txt
)
idp <- information_data_paragraph(ft)
expect_equal(
idp[idp$.part %in% "header",]$text.align,
rep("center", 16)
)
expect_equal(
idp[idp$.part %in% "body" & idp$.row_id < 6 & idp$.row_id > 1,]$text.align,
rep("center", 32)
)
})
test_that("package xtable", {
skip_if_not_installed("xtable")
require("xtable", quietly = TRUE)
tli <- data.frame(
grade = c(6L, 7L, 5L, 3L, 8L, 5L, 8L, 4L, 6L, 7L),
sex = factor(c("M", "M", "F", "M", "M", "M", "F", "M", "M", "M")),
disadvg = factor(c("YES", "NO", "YES", "YES", "YES", "NO", "YES", "YES", "NO", "YES")),
ethnicty = factor(
c(
"HISPANIC", "BLACK", "HISPANIC", "HISPANIC", "WHITE", "BLACK", "HISPANIC",
"BLACK", "WHITE", "HISPANIC"
),
levels = c("BLACK", "HISPANIC", "OTHER", "WHITE")
),
tlimth = c(43L, 88L, 34L, 65L, 75L, 74L, 72L, 79L, 88L, 87L)
)
tli.table <- xtable(tli)
align(tli.table) <- rep("r", 6)
align(tli.table) <- "|r|r|clr|r|"
ft <- as_flextable(
tli.table,
rotate.colnames = TRUE,
include.rownames = FALSE)
ft <- height(ft, i = 1, part = "header", height = 1)
idc <- information_data_chunk(ft)
expected_txt <- c(
"grade", "sex", "disadvg", "ethnicty", "tlimth", "6", "M",
"YES", "HISPANIC", "43", "7", "M", "NO", "BLACK", "88", "5",
"F", "YES", "HISPANIC", "34", "3", "M", "YES", "HISPANIC", "65",
"8", "M", "YES", "WHITE", "75", "5", "M", "NO", "BLACK", "74",
"8", "F", "YES", "HISPANIC", "72", "4", "M", "YES", "BLACK",
"79", "6", "M", "NO", "WHITE", "88", "7", "M", "YES", "HISPANIC",
"87"
)
expect_equal(
idc$txt,
expected_txt
)
idc <- information_data_cell(ft)
expect_equal(
idc$text.direction,
c(rep("btlr", 5), rep("lrtb", 50))
)
})
test_that("gam models", {
skip_if_not_installed("mgcv")
require("mgcv", quietly = TRUE)
set.seed(2)
dat <- gamSim(1, n = 400, dist = "normal", scale = 2)
b <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = dat)
options(show.signif.stars = FALSE)
ft <- as_flextable(b)
ft <- delete_part(ft, part = "footer")
idc <- information_data_chunk(ft)
expected_txt <- c(
"Component", "Term", "Estimate", "Std Error", "t-value", "p-value",
"A. parametric coefficients", "(Intercept)", "7.833", "0.099",
"79.303", "0.0000", "Component", "Term", "edf", "Ref. df", "F-value",
"p-value", "B. smooth terms", "s(x0)", "2.500", "3.115", "6.921",
"0.0001", "B. smooth terms", "s(x1)", "2.401", "2.984", "81.858",
"0.0000", "B. smooth terms", "s(x2)", "7.698", "8.564", "88.158",
"0.0000", "B. smooth terms", "s(x3)", "1.000", "1.000", "4.343",
"0.0378"
)
expect_equal(
idc$txt,
expected_txt
)
idp <- information_data_paragraph(ft)
expect_equal(
idp$text.align,
c(
"left", "left", "right", "right", "right", "right", "left",
"left", "right", "right", "right", "right", "left", "left", "right",
"right", "right", "right", "left", "left", "right", "right",
"right", "right", "left", "left", "right", "right", "right",
"right", "left", "left", "right", "right", "right", "right",
"left", "left", "right", "right", "right", "right"
)
)
})
flextable/tests/testthat/test-footnote.R 0000644 0001762 0000144 00000004127 14615445136 020174 0 ustar ligges users ft <- flextable(iris[1:5, ])
ft <- footnote(
x = ft, i = 1:3, j = 1:3,
ref_symbols = "a",
value = as_paragraph("This is footnote one")
)
text_data <- information_data_chunk(ft)
setDT(text_data)
test_that("symbols are inserted at the end", {
cell_1 <- text_data[.row_id %in% 1 & .col_id %in% "Sepal.Length" & .part %in% "body"]
expect_equal(cell_1$txt, c("5.1", "a"))
cell_2 <- text_data[.row_id %in% 2 & .col_id %in% "Sepal.Width" & .part %in% "body"]
expect_equal(cell_2$txt, c("3.0", "a"))
cell_3 <- text_data[.row_id %in% 3 & .col_id %in% "Petal.Length" & .part %in% "body"]
expect_equal(cell_3$txt, c("1.3", "a"))
})
test_that("footnotes are in the footer", {
cell_1 <- text_data[.part %in% "footer" & .col_id %in% "Sepal.Length"]
expect_equal(cell_1$txt, c("a", "This is footnote one"))
})
test_that("symbols are not inserted as a rectangular selection", {
cell_1 <- text_data[.row_id %in% 2 & .col_id %in% "Sepal.Length" & .part %in% "body"]
expect_equal(cell_1$txt, c("4.9"))
})
ft <- flextable(iris[1:5, ])
ft <- footnote(
x = ft, i = 1:3, j = 1:3,
ref_symbols = c("a", "b", "c"),
value = as_paragraph(paste("This is footnote", 1:3))
)
text_data <- information_data_chunk(ft)
setDT(text_data)
test_that("more than a symbol and more than a footnote", {
cell_1 <- text_data[.row_id %in% 1 & .col_id %in% "Sepal.Length" & .part %in% "body"]
expect_equal(cell_1$txt, c("5.1", "a"))
cell_2 <- text_data[.row_id %in% 2 & .col_id %in% "Sepal.Width" & .part %in% "body"]
expect_equal(cell_2$txt, c("3.0", "b"))
cell_3 <- text_data[.row_id %in% 3 & .col_id %in% "Petal.Length" & .part %in% "body"]
expect_equal(cell_3$txt, c("1.3", "c"))
note_1 <- text_data[.row_id %in% 1 & .part %in% "footer" & .col_id %in% "Sepal.Length"]
expect_equal(note_1$txt, c("a", "This is footnote 1"))
note_2 <- text_data[.row_id %in% 2 & .part %in% "footer" & .col_id %in% "Sepal.Length"]
expect_equal(note_2$txt, c("b", "This is footnote 2"))
note_3 <- text_data[.row_id %in% 3 & .part %in% "footer" & .col_id %in% "Sepal.Length"]
expect_equal(note_3$txt, c("c", "This is footnote 3"))
})
flextable/tests/testthat/test-rotations.R 0000644 0001762 0000144 00000004105 14615445175 020360 0 ustar ligges users dat <- data.frame(
a = c("left-top", "left-middle", "left-bottom"),
b = c("center-top", "center-middle", "center-bottom"),
c = c("right-top", "right-middle", "right-bottom")
)
ft_1 <- flextable(dat)
ft_1 <- theme_box(ft_1)
ft_1 <- height_all(x = ft_1, height = 1.3)
ft_1 <- hrule(ft_1, rule = "exact")
ft_1 <- rotate(ft_1, rotation = "tbrl")
ft_1 <- delete_part(ft_1)
ft_1 <- align(ft_1, j = 1, align = "left")
ft_1 <- align(ft_1, j = 2, align = "center")
ft_1 <- align(ft_1, j = 3, align = "right")
ft_1 <- valign(ft_1, i = 1, valign = "top")
ft_1 <- valign(ft_1, i = 2, valign = "center")
ft_1 <- valign(ft_1, i = 3, valign = "bottom")
test_that("docx rotations", {
tmp_docx <- tempfile(fileext = ".docx")
save_as_docx(ft_1, path = tmp_docx)
doc <- read_docx(tmp_docx)
docx <- docx_body_xml(doc)
valign_val <- xml_find_all(docx, "w:body/w:tbl/w:tr/w:tc/w:tcPr/w:vAlign")
valign_val <- xml_attr(valign_val, "val")
text_direction_val <- xml_find_all(docx, "w:body/w:tbl/w:tr/w:tc/w:tcPr/w:textDirection")
text_direction_val <- xml_attr(text_direction_val, "val")
align_val <- xml_find_all(docx, "w:body/w:tbl/w:tr/w:tc/w:p/w:pPr/w:jc")
align_val <- xml_attr(align_val, "val")
align <- c("left", "center", "right")
valign <- c("bottom", "center", "top")
expect_equal(valign_val, rep(valign, 3))
expect_equal(text_direction_val, rep("tbRl", 9))
expect_equal(align_val, rep(align, each = 3))
})
test_that("pptx rotations", {
tmp_pptx <- tempfile(fileext = ".pptx")
save_as_pptx(ft_1, path = tmp_pptx)
x <- read_pptx(tmp_pptx)
slide <- x$slide$get_slide(x$cursor)
doc <- slide$get()
cell_prs <- xml_find_all(doc, "//a:tbl/a:tr/a:tc/a:tcPr")
par_prs <- xml_find_all(doc, "//a:tbl/a:tr/a:tc/a:txBody/a:p/a:pPr")
text_direction_val <- xml_attr(cell_prs, "vert")
valign_val <- xml_attr(cell_prs, "anchor")
align_val <- xml_attr(par_prs, "algn")
align <- c("l", "ctr", "r")
valign <- c("b", "ctr", "t")
expect_equal(valign_val, rep(valign, 3))
expect_equal(text_direction_val, rep("vert", 9))
expect_equal(align_val, rep(align, each = 3))
})
flextable/tests/testthat/test-link.R 0000644 0001762 0000144 00000003035 14615445130 017263 0 ustar ligges users data <- data.frame(
code = c("X01", "X02"),
name = c("X Number 1", "X Number 2"),
stringsAsFactors = FALSE
)
url_base <- "https://example.com?/path&project=%s"
ft <- flextable(data)
ft <- mk_par(
x = ft,
j = ~code,
value = as_paragraph(
hyperlink_text(code, url = sprintf(url_base, code))
)
)
test_that("URL are preserved in docx", {
outfile <- tempfile(fileext = ".docx")
save_as_docx(ft, path = outfile)
doc <- read_docx(path = outfile)
body <- docx_body_xml(doc)
rid <- xml_attr(xml_find_all(body, "//w:hyperlink"), "id")
rels <- doc$doc_obj$rel_df()
urls <- rels[rels$id %in% rid, "target"]
expect_equal(urls, sprintf(url_base, data$code), ignore_attr = TRUE)
})
test_that("URL are preserved in pptx", {
outfile <- tempfile(fileext = ".pptx")
save_as_pptx(ft, path = outfile)
doc <- read_pptx(path = outfile)
xml_slide <- doc$slide$get_slide(1)$get()
rid <- xml_attr(xml_find_all(xml_slide, "//a:hlinkClick"), "id")
rels <- doc$slide$get_slide(1)$rel_df()
urls <- rels[rels$id %in% rid, "target"]
expect_equal(urls, sprintf(url_base, data$code), ignore_attr = TRUE)
})
test_that("URL are preserved in html", {
str_ <- flextable:::gen_raw_html(ft)
str_ <- gsub("", "", str_)
str_ <- gsub("", "", str_)
str_ <- gsub("", "", str_)
str_ <- gsub("