Only show first 10 rows in a gtsummary table?

146 Views Asked by At

I only want to show the first 10 rows of a gtsummary table. Is that possible?

data %>%
  select(anoobito, DESCRICAO) %>%
  tbl_summary(by = anoobito,
              label = c(DESCRICAO ~ "Causa Original")) %>%
  add_overall(last = T) %>%
  modify_table_body(fun = ~ dplyr::arrange(.x, desc(readr::parse_number(stat_0)))) %>%
  modify_spanning_header(c("stat_1":"stat_5") ~ "**Ano do Óbito**") %>%
  modify_header(label = '') %>%
  bold_labels() 

I've already ordered by descending order using modify_table_body(fun = ~ dplyr::arrange(.x, desc(readr::parse_number(stat_0)))), now I want to show the first 10 rows. Thanks.

EDIT: Some reproductible data:

dados <- data.frame(anoobito = c(2019, 2019, 2020, 2020, 2020, 2020, 2021, 2021, 2021, 2021, 2022,
                                 2022, 2022, 2022, 2022, 2022, 2022, 2023, 2023, 2023, 2023, 2023),
                    DESCRICAO = c("A150", "B250", "D349", "T980", "R99", "O988", "L99", "Q220", "F530", "P88",
                                  "A445", "K098", "G87", "I10", "A240", "Q88", "V633", "Z100", "I340", "L260", 
                                  "A150", "A150"))
2

There are 2 best solutions below

0
On BEST ANSWER

My preference is usually to summarize and arrange data prior to placing in a table. However, there may be an approach to modifying which rows are included in a displayed summary table.

First, store your table as tab:

library(gtsummary)
library(tidyverse)

tab <- dados %>%
  select(anoobito, DESCRICAO) %>%
  tbl_summary(by = anoobito,
              label = c(DESCRICAO ~ "Causa Original")) %>%
  add_overall(last = T) %>%
  modify_table_body(fun = ~ dplyr::arrange(.x, desc(readr::parse_number(stat_0)))) %>%
  modify_spanning_header(c("stat_1":"stat_5") ~ "**Ano do Óbito**") %>%
  modify_header(label = '') %>%
  bold_labels() 

Then, you can access a tibble inside of tab which contains the rows of results (table_body). Here you can substitute with the first 10 rows:

tab$table_body <- head(tab$table_body, 10)

Finally, show the new table tab result:

tab

Output

table summary including first 10 rows

1
On

You can try head(x,n=number). In this case n=10.

It works in a pipe cars |> head(n=10). Add head() after computations are performed or they will only apply to the sample.

See documentation for more.