1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
|
#' @export
#' @title data.frame automatic printing as a flextable
#' @description Create a summary from a data.frame as a flextable. This function
#' is to be used in an R Markdown document.
#'
#' To use that function, you must declare it in the part `df_print` of the 'YAML'
#' header of your R Markdown document:
#'
#' ```
#' ---
#' df_print: !expr function(x) flextable::df_printer(x)
#' ---
#' ```
#'
#' We notice an unexpected behavior with bookdown. When using bookdown it
#' is necessary to use [use_df_printer()] instead in a setup run chunk:
#'
#' ```
#' use_df_printer()
#' ```
#'
#' @param dat the data.frame
#' @param ... unused argument
#' @details
#' 'knitr' chunk options are available to customize the output:
#'
#' * `ft_max_row`: The number of rows to print. Default to 10.
#' * `ft_split_colnames`: Should the column names be split
#' (with non alpha-numeric characters). Default to FALSE.
#' * `ft_short_strings`: Should the character column be shorten.
#' Default to FALSE.
#' * `ft_short_size`: Maximum length of character column if
#' `ft_short_strings` is TRUE. Default to 35.
#' * `ft_short_suffix`: Suffix to add when character values are shorten.
#' Default to "...".
#' * `ft_do_autofit`: Use autofit() before rendering the table.
#' Default to TRUE.
#' * `ft_show_coltype`: Show column types.
#' Default to TRUE.
#' * `ft_color_coltype`: Color to use for column types.
#' Default to "#999999".
#' @family flextable print function
#' @examples
#' df_printer(head(mtcars))
df_printer <- function(dat, ...) {
args <- Filter(
function(z) !is.null(z),
list(
max_row = knitr::opts_current$get("ft_max_row"),
split_colnames = knitr::opts_current$get("ft_split_colnames"),
short_strings = knitr::opts_current$get("ft_short_strings"),
short_size = knitr::opts_current$get("ft_short_size"),
short_suffix = knitr::opts_current$get("ft_short_suffix"),
do_autofit = knitr::opts_current$get("ft_do_autofit"),
show_coltype = knitr::opts_current$get("ft_show_coltype"),
color_coltype = knitr::opts_current$get("ft_color_coltype")
)
)
args$x <- dat
if (is.null(knitr::pandoc_to())) {
message("this function is to be used in a knitr context.")
return(invisible(FALSE))
}
knitr::knit_print(
do.call(as_flextable, args)
)
}
#' @export
#' @title Set data.frame automatic printing as a flextable
#' @description Define [df_printer()] as data.frame
#' print method in an R Markdown document.
#'
#' In a setup run chunk:
#'
#' ```
#' flextable::use_df_printer()
#' ```
#' @seealso [df_printer()], [flextable()]
use_df_printer <- function() {
registerS3method("knit_print", "data.frame", df_printer)
registerS3method("knit_print", "data.table", df_printer)
registerS3method("knit_print", "tibble", df_printer)
registerS3method("knit_print", "grouped_df", df_printer)
registerS3method("knit_print", "spec_tbl_df", df_printer)
registerS3method("knit_print", "tbl", df_printer)
registerS3method("knit_print", "table", df_printer)
invisible()
}
look_like_int <- function(x) {
(is.numeric(x) && isTRUE(all.equal(x, as.integer(x)))) || is.integer(x)
}
multirow_df_printer <- function(dat,
max_row = 10,
split_colnames = FALSE,
short_strings = FALSE,
short_size = 35,
short_suffix = "...",
do_autofit = TRUE,
show_coltype = TRUE,
color_coltype = "#999999") {
x <- as.data.frame(dat)
nro <- nrow(x)
z <- get_flextable_defaults()
x <- head(x, n = max_row)
coltypes <- as.character(sapply(dat, function(x) head(class(x), 1)))
lli <- sapply(x, look_like_int)
x[lli] <- lapply(x[lli], as.integer)
if (!is.null(short_strings) && short_strings) {
wic <- sapply(x, is.character)
x[wic] <- lapply(x[wic], function(x) {
paste0(substring(text = x, first = 1, last = short_size), short_suffix)
})
}
colkeys <- colnames(x)
ft <- flextable(x, col_keys = colkeys)
if (split_colnames) {
labs <- strsplit(colkeys, split = "[^[:alnum:]]+")
names(labs) <- colkeys
labs <- lapply(labs, paste, collapse = "\n")
ft <- set_header_labels(ft, values = labs)
}
if (show_coltype) {
ft <- add_header_row(ft, top = FALSE, values = coltypes)
}
ft <- colformat_double(ft)
ft <- colformat_int(ft)
ft <- add_footer_lines(ft, values = sprintf("n: %.0f", nro))
ft <- set_table_properties(ft, layout = z$table.layout)
if ("fixed" %in% z$table.layout && do_autofit) {
ft <- autofit(ft)
}
ft <- do.call(z$theme_fun, list(ft))
if (show_coltype) {
ft <- color(ft, i = nrow_part(ft, "header"), part = "header", color = color_coltype)
}
ft <- align(ft, align = "left", part = "footer")
ft
}
singlerow_df_printer <- function(dat,
max_row = 10,
split_colnames = FALSE,
short_strings = FALSE,
short_size = 35,
short_suffix = "...",
do_autofit = TRUE,
show_coltype = TRUE,
color_coltype = "#999999") {
coltypes <- as.character(sapply(dat, function(x) head(class(x), 1)))
lli <- sapply(dat, look_like_int)
dat[lli] <- lapply(dat[lli], as.integer)
x <- data.frame(
"Col." = colnames(dat),
"Type" = coltypes,
"Val." = vapply(dat, format_fun.default, FUN.VALUE = NA_character_)
)
z <- get_flextable_defaults()
x <- head(x, n = max_row)
if (!is.null(short_strings) && short_strings) {
wic <- sapply(x, is.character)
x[wic] <- lapply(x[wic], function(x) {
paste0(substring(text = x, first = 1, last = short_size), short_suffix)
})
}
colkeys <- c("Col.", "Val.")
ft <- flextable(x, col_keys = colkeys)
ft <- delete_part(ft, part = "header")
ft <- set_table_properties(ft, layout = z$table.layout)
if ("fixed" %in% z$table.layout && do_autofit) {
ft <- autofit(ft)
}
ft <- do.call(z$theme_fun, list(ft))
ft <- align(ft, align = "center", part = "all")
ft <- align(ft, j = 1, align = "right", part = "all")
ft <- valign(x = ft, valign = "top", part = "body")
if (show_coltype) {
ft <- append_chunks(
x = ft, j = "Col.",
as_chunk("\n"),
colorize(
x = as_chunk(Type, props = fp_text_default(font.size = z$font.size * 2 / 3)),
color = color_coltype
)
)
}
ft
}
#' @export
#' @title Transform and summarise a 'data.frame' into a flextable
#' Simple summary of a data.frame as a flextable
#' @description It displays the first rows and shows the column types.
#' If there is only one row, a simplified vertical table is produced.
#' @param x a data.frame
#' @param max_row The number of rows to print. Default to 10.
#' @param split_colnames Should the column names be split
#' (with non alpha-numeric characters). Default to FALSE.
#' @param short_strings Should the character column be shorten.
#' Default to FALSE.
#' @param short_size Maximum length of character column if
#' `short_strings` is TRUE. Default to 35.
#' @param short_suffix Suffix to add when character values are shorten.
#' Default to "...".
#' @param do_autofit Use [autofit()] before rendering the table.
#' Default to TRUE.
#' @param show_coltype Show column types.
#' Default to TRUE.
#' @param color_coltype Color to use for column types.
#' Default to "#999999".
#' @param ... unused arguments
#' @examples
#' as_flextable(mtcars)
#' @family as_flextable methods
as_flextable.data.frame <- function(x,
max_row = 10,
split_colnames = FALSE,
short_strings = FALSE,
short_size = 35,
short_suffix = "...",
do_autofit = TRUE,
show_coltype = TRUE,
color_coltype = "#999999",
...) {
if (inherits(x, "data.table")) {
x <- as.data.frame(x)
} else if (inherits(x, "tbl_df")) {
x <- as.data.frame(x)
}
if (nrow(x) == 1) {
singlerow_df_printer(
dat = x,
max_row = max_row,
short_strings = short_strings,
short_size = short_size,
short_suffix = short_suffix,
do_autofit = do_autofit,
show_coltype = show_coltype,
color_coltype = color_coltype
)
} else {
multirow_df_printer(
dat = x,
max_row = max_row,
split_colnames = split_colnames,
short_strings = short_strings,
short_size = short_size,
short_suffix = short_suffix,
do_autofit = do_autofit,
show_coltype = show_coltype,
color_coltype = color_coltype
)
}
}
#' @export
#' @title Transform a 'table' object into a flextable
#' @description produce a flextable describing a
#' count table produced by function `table()`.
#'
#' This function uses the [proc_freq()] function.
#' @param x table object
#' @param ... arguments used by [proc_freq()].
#' @examples
#' tab <- with(warpbreaks, table(wool, tension))
#' ft <- as_flextable(tab)
#' ft
#' @family as_flextable methods
as_flextable.table <- function(x, ...) {
x <- as.data.frame(x)
by <- setdiff(colnames(x), "Freq")
if (length(by) > 2) {
stop("table must have maximum two dimensions.")
} else if (length(by) > 1) {
proc_freq(x, row = by[1], col = by[2], weight = "Freq", ...)
} else {
proc_freq(x, row = by[1], weight = "Freq", ...)
}
}
|