用于在R中使用Formattable包导出/保存表的命令 [英] Command for exporting/saving table made with Formattable package in R
问题描述
https://cran.r-project.org/web/ package / formattable / formattable.pdf
我一直在使用Formattable包在R中做一些漂亮的表。我试图保存表格作为图像(或真正的任何文件格式),但无法找到可用的命令。使用jpeg / png函数或dev.copy创建空白文档。理想情况下,我希望能够将这些表格保存在一个循环中。有没有人知道这可能如何完成?
I've been using the Formattable package to make some nice looking tables in R. I'm trying to save the tables as images (or really any file format) but can't find a command that works. Using the jpeg/png function or dev.copy creates blank documents. Ideally I'd like to be able to save these tables in a loop. Does anyone know how this might be done?
数据:
library(formattable)
DF <- data.frame(Ticker=c("", "", "", "IBM", "AAPL", "MSFT"),
Name=c("Dow Jones", "S&P 500", "Technology",
"IBM", "Apple", "Microsoft"),
Value=accounting(c(15988.08, 1880.33, NA,
130.00, 97.05, 50.99)),
Change=percent(c(-0.0239, -0.0216, 0.021,
-0.0219, -0.0248, -0.0399)))
formattable(DF, list(
Name=formatter(
"span",
style = x ~ ifelse(x == "Technology",
style(font.weight = "bold"), NA)),
Value = color_tile("white", "orange"),
Change = formatter(
"span",
style = x ~ style(color = ifelse(x < 0 , "red", "green")),
x ~ icontext(ifelse(x < 0, "arrow-down", "arrow-up"), x)))
)
推荐答案
为了保存formattable,您可以使用'as.htmlwidget '然后打印它。
首先运行下一个函数:
To save you formattable you can use 'as.htmlwidget' and then printscreen it. First run the next function:
library("htmltools")
library("webshot")
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)
}
来源: https://github.com/renkun-ken/formattable/issues/26)
然后在你的代码中,将formattable分配给变量,并使用该函数保存。
Then in your code assing the formattable to a variable and use the function to save it.
FT <- formattable(DF, list(
Name=formatter("span",
style = x ~ ifelse(x == "Technology", style(font.weight = "bold"), NA)),
Value = color_tile("white", "orange"),
Change = formatter("span",
style = x ~ style(color = ifelse(x < 0 , "red", "green")),
x ~ icontext(ifelse(x < 0, "arrow-down", "arrow-up"), x))) )
export_formattable(FT,"FT.png")
祝贺。
这篇关于用于在R中使用Formattable包导出/保存表的命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!