使用列表为kable

时间:2018-03-14 09:37:43

标签: r kable

我正在尝试使用k上的kable生成一个大表 我想使用存储在对象中的名称对某些行进行分组,但无法找到如何执行此操作。

这就是我所拥有的:

kable(Baseline, "html") %>%
  kable_styling("striped") %>%
  add_header_above(c(" " = 1, "My score" = 4)) %>%
  group_rows(index= c(" "=3, "Age" = 4, "BMI" = 4))

在这个例子中,我只有3个类别来对行进行子类化,但实际上我有更多想要知道是否可以调用包含名称和行数的对象而不是写出每个因素,如:

kable(Baseline, "html") %>%
  kable_styling("striped") %>%
  add_header_above(c(" " = 1, "My score" = 4)) %>%
  group_rows(index= nametable)

nametable包含与此名称对应的名称和行数。

希望这很清楚......

谢谢

2 个答案:

答案 0 :(得分:0)

使用虹膜数据集:

library(tidyverse)
library(kableExtra)

# split the dataset, creating a df for each category from the variable you'll use to group the rows
split_Table <- iris %>%
                split(.$Species) %>%
                discard(function(x) nrow(x) == 0) %>%
                map(., ~ select(., -Species)) # remove Species from split dfs

num_rows <- map(1:length(names(split_Table)), function(x){
             nrow(split_Table[[x]]) 
            }) %>% unlist()  # create function to count frequency of each category

split_Table %>%
 bind_rows() %>%
 kable("html", align = "c") %>%
 kable_styling(full_width = T) %>%
 group_rows(index = setNames(num_rows, names(split_Table)),
            label_row_css = "background-color: #666; color: #fff;") 
# create table with grouped rows

希望这会有所帮助!

答案 1 :(得分:0)

短一点...

library(tidyverse)
library(kableExtra)

counts <- table(iris$Species)

iris %>%
  arrange(Species)  %>%  # same order as table results  
  select(-Species)  %>%
  kable("html", align = "c") %>%
  kable_styling(full_width = T) %>%
  group_rows(index = setNames(counts, names(counts)),
             label_row_css = "background-color: #666; color: #fff;")