使用Formattable包在R中创建的表格导出/保存的命令

9

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)))
)

这看起来很像一个工具请求,很可能会被关闭。您可以通过添加一个小的可重现示例(数据和代码)来避免这种情况,该示例可以让您的“图像化”需求更加清晰明了。 - Roman Luštrik
1个回答

18

为了保存可格式化内容,您可以使用 '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)
    }

(来源: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")

最好的问候。


感谢分享,如果 value0,我们应该使用哪个图标?如何在您的代码中添加它? - ah bon
请问如何调整输出图像的宽高比? - ah bon
这对我很有效。旧的线程,所以回复的可能性很低,但是我怎样才能将PNG图像改为高分辨率,比如300dpi呢? - Mathew Vickers
1
@MathewVickers webshot函数有一个参数zoom,其中"缩放因子为2将导致垂直和水平方向上的像素数量增加一倍。" - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接