Search code examples
rplotformattable

No scrollbar for R formattable


I have a large dataframe that I presented as a formattable object. When the object renders in the R Studio viewer, I have a scrollbar to move up and down. But when I export the image it does not export the whole table, just a part of it. How can I export the whole table as an image?

Here is my code for the formattable object:

formattable(por.pais,align =c("c","c","c","c"),
        list('Equipo' = formatter("span", style = ~ style(color = "grey",font.weight ="bold")), 'Eficiencia'= color_tile(customRed, customGreen)))

And here is how R is exporting the image: formattable object


Solution

  • Ok so I found this code and it works to perfection:

    First, install the formattable, htmltools and webshot packages:

    install.packages("htmltools")
    install.packages("webshot")
    install.packages("formattable")
    

    Now load them:

    #Load the following libraries:
    library("htmltools")
    library("webshot")    
    

    Run the following function:

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

    Now, create a formattable object:

    tb <- formattable(dataframe)
    

    Fianlly, save your table as an image:

    export_formattable(tb,"my_table.png")
    

    Note: You can also use the .jpg extension.