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 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
|
#' Generic function to create formattable object
#'
#' This function is a generic function to create \code{formattable}
#' object, i.e. an object to which a formatting function and
#' related attribute are attached. The object works as ordinary object
#' yet has specially defined behavior as being printed or converted to
#' a string representation.
#'
#' @param x an object.
#' @param ... arguments to be passed to methods.
#' @export
#' @return a \code{formattable} object
formattable <- function(x, ...)
UseMethod("formattable")
#' Test for objects of 'formattable' class
#' @param x an object
#' @return \code{TRUE} if \code{x} has class 'formattable';
#' \code{FALSE} otherwise.
#' @export
#' @examples
#' is.formattable(10)
#' is.formattable(formattable(10))
is.formattable <- function(x) {
inherits(x, "formattable")
}
#' Create a formattable object
#' @inheritParams formattable
#' @param ... arguments to be passed to \code{formatter}.
#' @param formatter formatting function, \code{formatC} in default.
#' @param preproc pre-processor function that prepares \code{x} for
#' formatting function.
#' @param postproc post-processor function that transforms formatted
#' output for printing.
#' @export
#' @return a \code{formattable} object that inherits from the original
#' object.
#' @examples
#' formattable(rnorm(10), formatter = "formatC", digits = 1)
formattable.default <- function(x, ..., formatter,
preproc = NULL, postproc = NULL) {
create_obj(x, "formattable",
list(formatter = formatter,
format = list(...), preproc = preproc, postproc = postproc))
}
#' Create a formattable numeric vector
#' @inheritParams formattable.default
#' @param x a numeric vector.
#' @param formatter formatting function, \link{formatC} in default.
#' @export
#' @return a \code{formattable} numeric vector.
#' @examples
#' formattable(rnorm(10), format = "f", digits = 1)
#' formattable(rnorm(10), format = "f",
#' flag="+", digits = 1)
#' formattable(1:10,
#' postproc = function(str, x) paste0(str, "px"))
#' formattable(1:10,
#' postproc = function(str, x)
#' paste(str, ifelse(x <= 1, "unit", "units")))
formattable.numeric <- function(x, ..., formatter = "formatC",
preproc = NULL, postproc = NULL) {
create_obj(x, "formattable",
list(formatter = formatter,
format = list(...), preproc = preproc, postproc = postproc))
}
#' @export
formattable.table <- function(x, ..., formatter = "format",
preproc = NULL, postproc = NULL) {
create_obj(x, "formattable",
list(formatter = formatter,
format = list(...), preproc = preproc, postproc = postproc))
}
#' Create a formattable logical vector
#' @inheritParams formattable.default
#' @param x a logical vector.
#' @param formatter formatting function, \code{formattable::ifelse} in default.
#' @export
#' @return a \code{formattable} logical vector.
#' @examples
#' logi <- c(TRUE, TRUE, FALSE)
#' flogi <- formattable(logi, "yes", "no")
#' flogi
#' !flogi
#' any(flogi)
#' all(flogi)
formattable.logical <- function(x, ..., formatter = "ifelse",
preproc = NULL, postproc = NULL) {
create_obj(x, "formattable",
list(formatter = formatter,
format = list(...), preproc = preproc, postproc = postproc))
}
#' Create a formattable factor object
#' @inheritParams formattable.default
#' @param x a factor object.
#' @param formatter formatting function, \code{vmap} in default.
#' @export
#' @return a \code{formattable} factor object.
#' @examples
#' formattable(as.factor(c("a", "b", "b", "c")),
#' a = "good", b = "fair", c = "bad")
formattable.factor <- function(x, ..., formatter = "vmap",
preproc = NULL, postproc = NULL) {
create_obj(x, "formattable",
list(formatter = formatter,
format = list(...), preproc = preproc, postproc = postproc))
}
#' Create a formattable Date vector
#' @inheritParams formattable.default
#' @param x a vector of class \code{Date}.
#' @param formatter formatting function, \code{format.Date} in default.
#' @export
#' @return a \code{formattable} Date vector
#' @examples
#' dates <- as.Date("2015-04-10") + 1:5
#' fdates <- formattable(dates, format = "%m/%d/%Y")
#' fdates
#' fdates + 30
formattable.Date <- function(x, ..., formatter = "format.Date",
preproc = NULL, postproc = NULL) {
create_obj(x, "formattable",
list(formatter = formatter,
format = list(...), preproc = preproc, postproc = postproc))
}
#' Create a formattable POSIXct vector
#' @inheritParams formattable.default
#' @param x a vector of class \code{POSIXct}.
#' @param formatter formatting function, \code{format.POSIXct} in default.
#' @export
#' @return a \code{formattable} POSIXct vector
#' @examples
#' times <- as.POSIXct("2015-04-10 09:30:15") + 1:5
#' ftimes <- formattable(times, format = "%Y%m%dT%H%M%S")
#' ftimes
#' ftimes + 30
formattable.POSIXct <- function(x, ..., formatter = "format.POSIXct",
preproc = NULL, postproc = NULL) {
create_obj(x, "formattable",
list(formatter = formatter,
format = list(...), preproc = preproc, postproc = postproc))
}
#' Create a formattable POSIXlt vector
#' @inheritParams formattable.default
#' @param x a vector of class \code{POSIXlt}.
#' @param formatter formatting function, \code{format.POSIXlt} in default.
#' @export
#' @return a \code{formattable} POSIXlt vector
#' @examples
#' times <- as.POSIXlt("2015-04-10 09:30:15") + 1:5
#' ftimes <- formattable(times, format = "%Y%m%dT%H%M%S")
#' ftimes
#' ftimes + 30
formattable.POSIXlt <- function(x, ..., formatter = "format.POSIXlt",
preproc = NULL, postproc = NULL) {
create_obj(x, "formattable",
list(formatter = formatter,
format = list(...), preproc = preproc, postproc = postproc))
}
#' @export
formattable.formattable <- function(x, ..., formatter, preproc, postproc) {
attrs <- attr(x, "formattable", exact = TRUE)
if (is.null(attrs)) return(NextMethod("formattable"))
if (!missing(formatter)) attrs$formatter <- formatter
if (!missing(...)) attrs$format <- list(...)
if (!missing(preproc))
attrs$preproc <- if (is.list(preproc)) c(preproc, attrs$preproc) else preproc
if (!missing(postproc))
attrs$postproc <- if (is.list(postproc)) c(attrs$postproc, postproc) else postproc
attr(x, "formattable") <- attrs
x
}
#' @export
as.character.formattable <- function(x, ...) {
format.formattable(x)
}
print_formattable <- function(x, ...)
UseMethod("print_formattable")
print_formattable.default <- function(x, ...) {
if (length(x) == 0L) cat(sprintf("%s(0)", paste0(class(x), collapse = " ")))
else {
args <- list(...)
print_args <- attr(x, "formattable", exact = TRUE)$print
if (is.null(print_args)) print_args <- list()
print_args[names(args)] <- args
if (is.null(print_args$quote)) print_args$quote <- is.character(x)
do.call(print, c(list(format.formattable(x)), print_args))
}
invisible(x)
}
print_formattable.data.frame <- function(x, ...) {
print(as.htmlwidget(x), ...)
}
#' @export
print.formattable <- function(x, ...) {
print_formattable(x, ...)
}
knit_print_formattable <- function(x, ...)
UseMethod("knit_print_formattable")
knit_print_formattable.default <- print_formattable.default
#' @importFrom knitr asis_output
knit_print_formattable.data.frame <- function(x, ...) {
format <- attr(x, "formattable", exact = TRUE)$format
caption <- if (isTRUE(format$format == "pandoc" && nzchar(format$caption))) "<!-- -->\n\n" else ""
asis_output(sprintf("\n%s%s\n", caption, paste0(as.character(x), collapse = "\n")))
}
#' @export
#' @importFrom knitr knit_print
knit_print.formattable <- function(x, ...)
knit_print_formattable(x, ...)
#' @export
format.formattable <- function(x, ...,
format = NULL,
justify = "none", na.encode = FALSE, trim = FALSE, use.names = TRUE) {
attrs <- attr(x, "formattable", exact = TRUE)
if (length(x) == 0L || is.null(attrs) || is.null(attrs$formatter))
return(NextMethod("format"))
format_args <- attrs$format
format_args[names(format)] <- format
value <- remove_class(x, "formattable")
if (length(attrs$preproc)) {
preproc_list <- if (is.list(attrs$preproc)) attrs$preproc else list(attrs$preproc)
for (preproc in preproc_list) value <- call_or_default(preproc, value)
}
str <- do.call(attrs$formatter, c(list(value), format_args))
if (x_atomic <- is.atomic(x)) str <- remove_attribute(str, "formattable")
if (length(attrs$postproc)) {
postproc_list <- if (is.list(attrs$postproc)) attrs$postproc else list(attrs$postproc)
for (postproc in postproc_list) str <- call_or_default(postproc, str, value)
}
str <- as.character(str)
if (x_atomic) {
str <- copy_dim(x, str, use.names)
}
str
}
#' @export
as.list.formattable <- function(x, ...) {
lapply(seq_along(x), function(i) x[[i]])
}
#' @export
`[.formattable` <- function(x, ...) {
value <- NextMethod("[")
if (is.atomic(x) || is.data.frame(x))
copy_obj(x, value, "formattable")
else value
}
#' @export
`[<-.formattable` <- function(x, ..., value) {
value <- NextMethod("[<-")
reset_class(x, value, "formattable")
}
#' @export
`[[.formattable` <- function(x, ...) {
value <- NextMethod("[[")
if (is.atomic(x))
copy_obj(x, value, "formattable")
else value
}
#' @export
`[[<-.formattable` <- function(x, ..., value) {
value <- NextMethod("[[<-")
reset_class(x, value, "formattable")
}
#' @export
c.formattable <- function(..., recursive = FALSE) {
fcreate_obj(c, "formattable", ...)
}
#' @export
`+.formattable` <- function(x, y) {
cop_create_obj(`+`, "formattable", x, y)
}
#' @export
`-.formattable` <- function(x, y) {
cop_create_obj(`-`, "formattable", x, y)
}
#' @export
`*.formattable` <- function(x, y) {
cop_create_obj(`*`, "formattable", x, y)
}
#' @export
`/.formattable` <- function(x, y) {
fcreate_obj(`/`, "formattable", x, unclass(y))
}
#' @export
`%%.formattable` <- function(x, y) {
fcreate_obj(`%%`, "formattable", x, unclass(y))
}
#' @export
rep.formattable <- function(x, ...) {
fcreate_obj(rep, "formattable", x, ...)
}
#' @export
`&.formattable` <- function(x, y) {
fcreate_obj(`&`, "formattable", x, unclass(y))
}
#' @export
`|.formattable` <- function(x, y) {
fcreate_obj(`|`, "formattable", x, unclass(y))
}
#' @export
all.formattable <- function(...) {
fcreate_obj(all, "formattable", ...)
}
#' @export
any.formattable <- function(...) {
fcreate_obj(any, "formattable", ...)
}
#' @export
max.formattable <- function(...) {
fcreate_obj(max, "formattable", ...)
}
#' @export
min.formattable <- function(...) {
fcreate_obj(min, "formattable", ...)
}
#' @export
sum.formattable <- function(...) {
fcreate_obj(sum, "formattable", ...)
}
#' @export
mean.formattable <- function(x, ...) {
fcreate_obj(mean, "formattable", x, ...)
}
#' @export
unique.formattable <- function(x, ...) {
fcreate_obj(unique, "formattable", x, ...)
}
#' @export
diff.formattable <- function(x, ...) {
fcreate_obj(diff, "formattable", x, ...)
}
#' @export
cummax.formattable <- function(x, ...) {
fcreate_obj(cummax, "formattable", x, ...)
}
#' @export
cummin.formattable <- function(x, ...) {
fcreate_obj(cummin, "formattable", x, ...)
}
#' @export
cumsum.formattable <- function(x, ...) {
fcreate_obj(cumsum, "formattable", x, ...)
}
#' @importFrom stats median
#' @export
median.formattable <- function(x, ...) {
fcreate_obj(median, "formattable", x, ...)
}
#' @importFrom stats quantile
#' @export
quantile.formattable <- function(x, ...) {
fcreate_obj(quantile, "formattable", x, ...)
}
render_html_matrix <- function(x, ...)
UseMethod("render_html_matrix")
render_html_matrix.data.frame <- function(x, formatters = list(), digits = getOption("digits"), ...) {
stopifnot(is.data.frame(x))
if (nrow(x) == 0L) formatters <- list()
cols <- colnames(x)
mat <- vapply(x, format, character(nrow(x)), digits = digits, trim = TRUE)
dim(mat) <- dim(x)
dimnames(mat) <- dimnames(x)
for (fi in seq_along(formatters)) {
fn <- names(formatters)[[fi]]
f <- formatters[[fi]]
if (is_false(f)) next
else if (!is.null(fn) && nzchar(fn)) {
if (fn %in% cols) {
value <- x[[fn]]
fv <- if (inherits(f, "formatter")) f(value, x, mat[, fn])
else if (inherits(f, "formula")) eval_formula(f, value, x)
else match.fun(f)(value)
mat[, fn] <- format(fv)
}
} else if (inherits(f, "formula")) {
fenv <- environment(f)
value <- as.matrix(if (length(f) == 2L) {
row <- col <- TRUE
f <- eval(f[[2L]], fenv)
x
} else {
if (is.call(f[[2L]])) {
farea <- eval(f[[2L]], fenv)
if (inherits(farea, "area")) {
row <- eval(farea$row, seq_list(rownames(x)), farea$envir)
col <- eval(farea$col, seq_list(colnames(x)), farea$envir)
f <- eval(f[[3L]], fenv)
x[row, col]
} else {
stop("Invalid area formatter specification. Use area(row, col) ~ formatter instead.", call. = FALSE)
}
} else {
stop("Invalid formatter specification. Use area(row, col) ~ formatter instead.", call. = FALSE)
}
})
fv <- if (inherits(f, "formatter"))
f(value, x, mat[row, col]) else match.fun(f)(value)
mat[row, col] <- format(fv)
}
}
nulls <- get_false_entries(formatters)
mat[, setdiff(cols, nulls), drop = FALSE]
}
render_html_matrix.formattable <- function(x, ...) {
stopifnot(is.formattable(x), is.data.frame(x))
do.call(render_html_matrix.data.frame,
c(list(x = remove_class(x, "formattable")), attr(x, "formattable")$format))
}
#' Format a data frame with formatter functions
#'
#' This is an table generator that specializes in creating
#' formatted table presented in HTML by default.
#' To generate a formatted table, columns or areas of the
#' input data frame can be transformed by formatter functions.
#' @importFrom knitr kable
#' @param x a \code{data.frame}.
#' @param formatters a list of formatter functions or formulas.
#' The existing columns of \code{x} will be applied the formatter
#' function in \code{formatters} if it exists.
#'
#' If a formatter is specified by formula, then the formula will be
#' interpreted as a lambda expression with its left-hand side being
#' a symbol and right-hand side being the expression using the symbol
#' to represent the column values. The formula expression will be evaluated
#' in the environment of the formula.
#'
#' If a formatter is \code{FALSE}, then the corresponding column will be hidden.
#'
#' Area formatter is specified in the form of
#' \code{area(row, col) ~ formatter} without specifying the column name.
#' @param format The output format: html, markdown or pandoc?
#' @param align The alignment of columns: a character vector consisting
#' of \code{'l'} (left), \code{'c'} (center), and/or \code{'r'} (right).
#' By default, all columns are right-aligned.
#' @param ... additional parameters to be passed to \code{knitr::kable}.
#' @param digits The number of significant digits to be used for numeric
#' and complex values.
#' @param table.attr The HTML class of \code{<table>} created when
#' \code{format = "html"}
#' @return a \code{knitr_kable} object whose \code{print} method generates a
#' string-representation of \code{data} formatted by \code{formatter} in
#' specific \code{format}.
#' @export
#' @examples
#' # mtcars (mpg in red)
#' format_table(mtcars,
#' list(mpg = formatter("span", style = "color:red")))
#'
#' # mtcars (mpg in red if greater than median)
#' format_table(mtcars, list(mpg = formatter("span",
#' style = function(x) ifelse(x > median(x), "color:red", NA))))
#'
#' # mtcars (mpg in red if greater than median, using formula)
#' format_table(mtcars, list(mpg = formatter("span",
#' style = x ~ ifelse(x > median(x), "color:red", NA))))
#'
#' # mtcars (mpg in gradient: the higher, the redder)
#' format_table(mtcars, list(mpg = formatter("span",
#' style = x ~ style(color = rgb(x/max(x), 0, 0)))))
#'
#' # mtcars (mpg background in gradient: the higher, the redder)
#' format_table(mtcars, list(mpg = formatter("span",
#' style = x ~ style(display = "block",
#' "border-radius" = "4px",
#' "padding-right" = "4px",
#' color = "white",
#' "background-color" = rgb(x/max(x), 0, 0)))))
#'
#' # mtcars (mpg in red if vs == 1 and am == 1)
#' format_table(mtcars, list(mpg = formatter("span",
#' style = ~ style(color = ifelse(vs == 1 & am == 1, "red", NA)))))
#'
#' # hide columns
#' format_table(mtcars, list(mpg = FALSE, cyl = FALSE))
#'
#' # area formatting
#' format_table(mtcars, list(area(col = vs:carb) ~ formatter("span",
#' style = x ~ style(color = ifelse(x > 0, "red", NA)))))
#'
#' df <- data.frame(a = rnorm(10), b = rnorm(10), c = rnorm(10))
#' format_table(df, list(area() ~ color_tile("transparent", "lightgray")))
#' format_table(df, list(area(1:5) ~ color_tile("transparent", "lightgray")))
#' format_table(df, list(area(1:5) ~ color_tile("transparent", "lightgray"),
#' area(6:10) ~ color_tile("transparent", "lightpink")))
#' @seealso \link{formattable}, \link{area}
format_table <- function(x, formatters = list(),
format = c("html", "markdown", "pandoc"), align = "r", ...,
digits = getOption("digits"), table.attr = 'class="table table-condensed"') {
format <- match.arg(format)
mat <- render_html_matrix(x, formatters, digits)
kable(mat, format = format, align = align, escape = FALSE, ...,
table.attr = table.attr)
}
#' Create a formattable data frame
#'
#' This function creates a formattable data frame by attaching
#' column or area formatters to the data frame. Each time the data frame
#' is printed or converted to string representation, the formatter
#' function will use the formatter functions to generate
#' formatted cells.
#'
#' @details
#' The formattable data frame is a data frame with lazy-bindings
#' of prespecified column formatters or area formatters.
#' The formatters will not be applied until the data frame is
#' printed to console or in a dynamic document. If the formatter
#' function has no side effect, the formattable data frame will
#' not be changed even if the formatters are applied to produce
#' the printed version.
#'
#' @inheritParams formattable.default
#' @param x a \code{data.frame}
#' @param formatter formatting function, \code{format_table} in default.
#' @export
#' @return a \code{formattable data.frame}
#' @examples
#' # mtcars (mpg in red)
#' formattable(mtcars,
#' list(mpg = formatter("span", style = "color:red")))
#'
#' # mtcars (mpg in red if greater than median)
#' formattable(mtcars, list(mpg = formatter("span",
#' style = function(x) ifelse(x > median(x), "color:red", NA))))
#'
#' # mtcars (mpg in red if greater than median, using formula)
#' formattable(mtcars, list(mpg = formatter("span",
#' style = x ~ ifelse(x > median(x), "color:red", NA))))
#'
#' # mtcars (mpg in gradient: the higher, the redder)
#' formattable(mtcars, list(mpg = formatter("span",
#' style = x ~ style(color = rgb(x/max(x), 0, 0)))))
#'
#' # mtcars (mpg background in gradient: the higher, the redder)
#' formattable(mtcars, list(mpg = formatter("span",
#' style = x ~ style(display = "block",
#' "border-radius" = "4px",
#' "padding-right" = "4px",
#' color = "white",
#' "background-color" = rgb(x/max(x), 0, 0)))))
#'
#' # mtcars (mpg in red if vs == 1 and am == 1)
#' formattable(mtcars, list(mpg = formatter("span",
#' style = ~ style(color = ifelse(vs == 1 & am == 1, "red", NA)))))
#'
#' # hide columns
#' formattable(mtcars, list(mpg = FALSE, cyl = FALSE))
#'
#' # area formatting
#' formattable(mtcars, list(area(col = vs:carb) ~ formatter("span",
#' style = x ~ style(color = ifelse(x > 0, "red", NA)))))
#'
#' df <- data.frame(a = rnorm(10), b = rnorm(10), c = rnorm(10))
#' formattable(df, list(area() ~ color_tile("transparent", "lightgray")))
#' formattable(df, list(area(1:5) ~ color_tile("transparent", "lightgray")))
#' formattable(df, list(area(1:5) ~ color_tile("transparent", "lightgray"),
#' area(6:10) ~ color_tile("transparent", "lightpink")))
#' @seealso \link{format_table}, \link{area}
formattable.data.frame <- function(x, ..., formatter = "format_table",
preproc = NULL, postproc = NULL) {
create_obj(x, "formattable",
list(formatter = formatter, format = list(...),
preproc = preproc, postproc = postproc))
}
|