Fáb*_*les 5 r knitr formattable
我开始使用R formattable包,但仍然面临一些问题,无法formattable()正确输出 pdf 文档。
第一个问题:在应用任何color_*仅适用于数字类的函数后,如何获得百分比格式的数字?
从在R环境中执行/运行的代码中查看下表。
a<-formattable(x=a,list(A=color_bar("orange", 0.2),B=color_bar("orange", 0.2),C=color_bar("orange", 0.2),D=color_bar("orange", 0.2),E=color_bar("orange", 0.2)))
Run Code Online (Sandbox Code Playgroud)
假设a作为csv我输入的文件read.csv()。
我想让“%”将数字粘贴在一起,同时将橙色条从 粘贴在一起formattable,但是如果我将 转换numeric为percentby percent()fromscale或 by paste(a,"%",sep="")formattable 将无法正常工作numeric,需要进行指责。
第二个问题:渲染为 pdf 时,未正确创建来自呈现的块的此类表。我尝试使用formattable(a,list...), byprint(a)和 by 的直接输出,print(xtable(a))但没有任何效果。任何提示?
问题第一部分的解决方案:
df <- data.frame(
id = 1:10,
A = sample(20:80, 10),
B = sample(1:1000, 10),
C = sample(1:10, 10),
D = percent(runif(10, 0, 1), format = "d"),
E = percent(runif(10, 0, 1), format = "d"),
stringsAsFactors = FALSE)
formattable(df, list(
A = color_tile("black", 0.2),
B = color_tile("pink", 0.2),
C = color_tile("orange", "gray"),
D = color_tile("blue", 0.2),
E = color_tile("green", 0.2)))
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅文档:https://github.com/renkun-ken/formattable
关于 pdf 渲染 - 您始终可以将表格设为“htmlwidget”,然后将其制作为 pdf 打印屏幕。在 R 中你可以尝试这个函数(来源):
#' Export a Formattable as PNG, PDF, or JPEG
#'
#' @param f A formattable.
#' @param file Export path with extension .png, .pdf, or .jpeg.
#' @param width Width specification of the html widget being exported.
#' @param height Height specification of the html widget being exported.
#' @param background Background color specification.
#' @param delay Time to wait before taking webshot, in seconds.
#'
#' @importFrom formattable as.htmlwidget
#' @importFrom htmltools html_print
#' @importFrom webshot webshot
#'
#' @export
export_formattable <- function(f, file, width = "100%", height = NULL,
background = "white", delay = 0.2)
{
w <- as.htmlwidget(f, width = width, height = height)
path <- html_print(w, background = background, viewer = NULL)
url <- paste0("file:///", gsub("\\\\", "/", normalizePath(path)))
webshot(url,
file = file,
selector = ".formattable_widget",
delay = delay)
}
Run Code Online (Sandbox Code Playgroud)