【问题标题】:How to have R formattable rendered to pdf output and how to have percents in the table如何将 R 格式表呈现为 pdf 输出以及如何在表格中显示百分比
【发布时间】:2016-01-25 01:32:20
【问题描述】:

我开始使用 R formattablepackage 并且仍然面临一些问题,因为 formattable() 正确输出 pdf 文档时遇到了一些问题。

第一个问题:在应用任何仅适用于数字类的color_* 函数后,如何获得百分比格式的数字?

从Renviroment 中执行/运行的代码中查看下表。

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

假设a 是我通过read.csv() 输入的csv文件。

我希望将“%”和formattable 中的橙色条粘贴在一起,但如果我将percent() 中的scale 中的percent() 转换为percent或paste(a,"%",sep="") formattable 将无法正常工作,因为需要numeric。

第二个问题:当呈现为 pdf 时,来自所呈现块的此类表未正确创建。我尝试使用来自formattable(a,list...)、print(a) 和print(xtable(a)) 的直接输出,但没有以任何方式工作。有什么提示吗?

【问题讨论】:

    标签: r knitr formattable


    【解决方案1】:

    您问题第一部分的解决方案:

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

    有关详细信息,请参阅文档:https://github.com/renkun-ken/formattable

    关于 pdf 渲染 - 您始终可以将您的表格设置为“htmlwidget”,然后将其制作为 pdf 打印屏幕。在 R 中你可以试试这个函数(source):

    #' 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)
    }
    

    【讨论】:

    • 当我尝试这个问题的第二部分时,它只输出没有我的条件格式颜色的表格。我是不是用错了新功能?
    猜你喜欢
    • 1970-01-01
    • 2013-08-26
    • 2011-11-01
    • 1970-01-01
    • 2012-02-18
    • 1970-01-01
    • 1970-01-01
    • 2021-08-12
    • 1970-01-01
    相关资源
    最近更新 更多