【问题标题】:Command for exporting/saving table made with Formattable package in RR中使用Formattable包制作的导出/保存表格的命令
【发布时间】:2016-12-14 11:10:25
【问题描述】:

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

【问题讨论】:

  • 这看起来很像一个工具请求,必然会被关闭。您可以通过添加一个您想要“想象”的小型可重现示例(数据和代码)来避免它。

标签: r save export formattable


【解决方案1】:

为了保存你的格式,你可以使用'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,我们应该使用哪个图标?如何将其添加到您的代码中?
  • 请问如何调整输出图片的宽高比?
猜你喜欢
  • 2021-12-06
  • 1970-01-01
  • 1970-01-01
  • 2016-05-05
  • 1970-01-01
  • 1970-01-01
  • 2017-12-23
  • 1970-01-01
  • 2021-12-05
相关资源
最近更新 更多