2

我正在尝试使用 R 上的 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 包含与该名称对应的名称和行数。

希望这很清楚...

谢谢

4

2 回答 2

1

有点短...

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;") 
于 2018-10-23T15:48:15.337 回答
0

使用 iris 数据集:

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

希望这可以帮助!

于 2018-08-08T19:12:49.290 回答