Table formats

· 1566 words · 4 minute read

学习总结利用DT包和r2rtf包对表格进行自定义格式: 高亮行列、单元格;字体加粗/斜体; 单元格靠左/右/居中。两个包的应用场景不同。其中,DT包可以将R对象(矩阵或数据框)输出为html格式的表格并在浏览器中展示,可提供一些交互式行为(如筛选,排序等);r2rtf (as the name indicates)可以将用户自定义的R数据框输出为rtf格式,通常用于报告中。

DT 🔗

看一下版本信息:

# if (!require("DT")) install.packages('DT')
xfun::session_info('DT')
## R version 4.1.2 (2021-11-01)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## Running under: Windows 10 x64 (build 19045)
## 
## Locale:
##   LC_COLLATE=Chinese (Simplified)_China.936 
##   LC_CTYPE=Chinese (Simplified)_China.936   
##   LC_MONETARY=Chinese (Simplified)_China.936
##   LC_NUMERIC=C                              
##   LC_TIME=Chinese (Simplified)_China.936    
## 
## Package version:
##   base64enc_0.1.3   bslib_0.5.0       cachem_1.0.6      cli_3.6.0        
##   crosstalk_1.2.0   digest_0.6.29     DT_0.20           ellipsis_0.3.2   
##   evaluate_0.21     fastmap_1.1.0     fontawesome_0.5.1 fs_1.5.2         
##   glue_1.6.2        graphics_4.1.2    grDevices_4.1.2   highr_0.10       
##   htmltools_0.5.4   htmlwidgets_1.6.2 jquerylib_0.1.4   jsonlite_1.8.4   
##   knitr_1.42        later_1.3.0       lazyeval_0.2.2    lifecycle_1.0.3  
##   magrittr_2.0.3    memoise_2.0.1     methods_4.1.2     mime_0.12        
##   promises_1.2.0.1  R6_2.5.1          rappdirs_0.3.3    Rcpp_1.0.10      
##   rlang_1.1.1       rmarkdown_2.22    sass_0.4.2        stats_4.1.2      
##   stringi_1.7.6     stringr_1.5.0     tinytex_0.45      tools_4.1.2      
##   utils_4.1.2       vctrs_0.5.2       xfun_0.36         yaml_2.2.1

用到的样例数据:

head(mtcars)
##                    mpg cyl disp  hp drat    wt  qsec vs am gear carb
## Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
## Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
## Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
## Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
## Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
## Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

Pagelength、lengthmenu 🔗

datatables默认的pageLength等于10(显示前10行数据),lengthMenu 为c(10,25,50,100)。咱可以利用在datattable函数里面增加options参数来DIY pageLength和lengthMenu。

 options = list(
                  pageLength = 5,
                  lengthMenu = c(5, 15, 100)
                 )

默认输出:

library(dplyr)
## Warning: 程辑包'dplyr'是用R版本4.1.3 来建造的

## 
## 载入程辑包:'dplyr'

## The following objects are masked from 'package:stats':
## 
##     filter, lag

## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
dat <- mtcars %>% 
  mutate(brand = rownames(.)) 

dat %>% 
  DT::datatable(rownames = FALSE)

自定义pagelength和pagemenu:

dat %>% 
  DT::datatable(
    rownames = FALSE,
    options = list(
                  pageLength = 5,
                  lengthMenu = c(5, 15, 100)
                 )
  )

filter 🔗

在表格的顶部or底部增加数据筛选功能:

dat %>% 
  DT::datatable(
    rownames = FALSE,
    filter = 'top',
    options = list(
                  pageLength = 2,
                  lengthMenu = c(5, 15, 100)
                 )
  )
dat %>% 
  DT::datatable(
    rownames = FALSE,
    filter = 'bottom',
    options = list(
                  pageLength = 2,
                  lengthMenu = c(5, 15, 100)
                 )
  )

Add buttons 🔗

❗ 默认情况下,DOM输出length menu, 搜索框,表格,信息汇总,页码控制这五个元素。如果需要增加按钮,用户需要自定义options中的dom参数。

dom 用于控制表格输出内容/元素以及元素的顺序。其中: l - length changing input control f - filtering input t - The table! i - Table information summary p - pagination control r - processing display element

dat %>% 
  DT::datatable(
    rownames = FALSE,
    filter = 'top',
    extensions = 'Buttons',
    options = list(dom = 'Blftrip',
                   buttons = c('copy', 'csv', 'excel', 'pdf', 'print'),
                   lengthMenu = c(5,15,100)
                   )
  )

format*() 格式定义货币,百分比和小数和时间 🔗

special character unicode/JS

# m = c('toDateString', 'toLocaleDateString', 'toLocaleString', 'toUTCString')
dat %>% 
  DT::datatable(rownames = FALSE,
                options = list(dom = 'tip',
                               pageLength=5)) %>% 
  DT::formatCurrency(c('mpg', 'cyl'),c('\U20AC','\u00A5'),digits = c(0,2)) %>% 
  DT::formatPercentage('drat', digits = 1) %>% 
  DT::formatRound('wt', digits = 3)
  #%>%  formatDate(1:4, m)
  
  #toDateString: Fri Jul 24 2015	
  #toLocaleDateString: 2015/7/24	
  #toLocaleString: 2015/7/24 11:05:22	
  #toUTCString: Fri, 24 Jul 2015 03:05:22 GMT

formatStyle() 🔗

可以用来改变列的CSS。常见的参数包括:文字颜色 color, 文字加粗fontWeight,背景高亮 backgroundColor。如果需要根据变量取值对文本的CSS进行定制化,定义参数时则需要用到styleInterval()函数。

下面的例子展示以整列为单位进行CSS format:

  1. 对变量dratwt按照3来分为两类,并对应标记未粉红色或者浅蓝色;
  2. 对cyl==6的观测行进行高亮粉色,cyl==8的进行天蓝色高亮。需要用到styleEqual函数;
  3. 用柱状图展示变量qsec:需要在background参数里用到styleColorBar函数
dat$index <- case_when(dat$cyl ==6 ~'cyl==6',
                       dat$cyl==8~'cyl==8',
                       TRUE ~ "others"
                       )

dat %>% 
  DT::datatable(rownames = FALSE,
                options = list(dom = 'tip',
                               pageLength=5)) %>% 
  DT::formatStyle(c('drat','wt'),
                  color = DT::styleInterval(c(3),c("pink","lightblue")) ) %>% 
  DT::formatStyle("cyl", ## 这里是给第一个变量加高亮,没有用到c()
                  backgroundColor = DT::styleEqual(c(6,8),c("pink","lightblue")  )) %>% 
  DT::formatStyle('qsec',
                  background = DT::styleColorBar(dat$qsec,'pink')
                  )

默认情况下,background属性会在水平和垂直方向上重复图像,如果垂直重复就会显得很拥挤(可以看到qsec的柱状图每一个挨着很拥挤)我们可以通过在formatStyle函数里面使用backgroundSize,backgroundRepeat和backgroundPosition 参数控制柱状图的相对大小,位置。 另外,

dat %>% 
  DT::datatable(rownames = FALSE,
                options = list(dom = 'tip',
                               pageLength=5)) %>% 
  DT::formatStyle('qsec',
                  background = DT::styleColorBar(dat$qsec,'pink'),
                 backgroundSize = '100% 80%',
                 backgroundRepeat = 'no-repeat', #, #no-repeat 只显示一次, repeat-y 垂直重复; repeat-x 水平重复
                backgroundPosition = 'center'
                  
                  )