用R中的Formattable软件包制作的导出/保存表的命令

Lau*_*a D 6 export r save formattable

https://cran.r-project.org/web/packages/formattable/formattable.pdf

我一直在使用Formattable包在R中制作一些漂亮的表。我试图将这些表另存为图像(或实际上任何文件格式),但找不到有效的命令。使用jpeg / png函数或dev.copy创建空白文档。理想情况下,我希望能够将这些表循环保存。有谁知道该怎么做?

数据:

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)))
)
Run Code Online (Sandbox Code Playgroud)

faa*_*yan 7

要保存格式表,可以使用“ as.htmlwidget”,然后对其进行屏幕打印。首先运行下一个函数:

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)
    }
Run Code Online (Sandbox Code Playgroud)

(来源:https : //github.com/renkun-ken/formattable/issues/26

然后在代码中将formattable赋给变量,然后使用该函数保存它。

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")
Run Code Online (Sandbox Code Playgroud)

最好的祝福。