如何导出50行tableGrob-table

时间:2018-04-05 12:23:06

标签: r gridextra

我有一个50行表tableGrob().

表本身适用于目的,两个第一列对齐左侧,其余三列居中。

问题在于我无法导出它(我更喜欢像PNGJPEG这样的东西。当我尝试时,我只得到它的一小部分!

非常感谢任何帮助。

library(gridExtra) 
library(grid)

myiris1 <- iris[1:50,1:2] # df with columns to be aligned to the left 
myiris2 <- iris[1:50,3:5] # df with columns to be centered  

tt3 <- ttheme_default(core=list(fg_params=list(hjust=0, x=0.1)),    # theme for alignment to the left 
                      colhead=list(fg_params=list(hjust=0, x=0.1))) 

g1 <- tableGrob(myiris1,rows = NULL,theme=tt3) # table with columns aligned to the left
g2 <- tableGrob(myiris2,rows = NULL) # table with columns centered (by default) 

haligned <- gtable_combine(g1,g2, along=1) # align the two tables horizontally to make a single table  
grid.arrange(haligned, ncol=1)

1 个答案:

答案 0 :(得分:1)

您可以使用tableHTML创建此类表格:

iris[1:50, ] %>% 
# create tableHTML without rownames
tableHTML(rownames = FALSE) %>% 
# add lightgray background to every 2nd row
  add_css_row(css = list(c('background-color'), c('lightgray')), 
              rows = even(1:50)) %>% 
# align the text of columns 3:5
  add_css_column(columns = 3:5,
                 css = list(c('text-align'),
                            c('center'))) %>% 
# use html tools to print to the viewer
  htmltools::html_print()

然后只需点击导出即可创建PNG

export_button

另一种方法是使用webshot将HTML文件转换为PNG:

iris[1:50, ] %>% 
 tableHTML(rownames = FALSE) %>% 
  add_css_row(css = list(c('background-color'), c('lightgray')), 
              rows = even(1:50)) %>% 
  add_css_column(columns = 3:5,
                 css = list(c('text-align'),
                            c('center'))) %>% 
  write_tableHTML(file = "table.html", complete_html = TRUE)

webshot::webshot("table.html")

然后,您将在工作目录中找到名为webshot.png的文件。