gt - summary_rows() counts

Can't figure out how to add a summary function to count the rows in a group...

Try using the length() function.

With the following:

you are attempting to place the summary result in a column that is hidden. Try using columns = vars(num) instead.

Thanks for the workaround. As you note, it works, except that the length function only works if the your dataset has a disposable numeric variable to use with the columns parameter, and the count comes out with two trailing zeros.

As you work on a fix, I'd suggest that counting the rows in a group would be a common use case for a summary_rows function.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

I got length() to work as a grand summary:

library(tidyverse)
library(gt)
exibble %>% select(group, char, date, num) %>% 
  gt(groupname_col = "group") %>%
  summary_rows(
    groups = NULL,
    columns = vars(num),
    fns = list(len = ~length(.)
    ))
char date num
grp_a
apricot 2015-01-15 1.111e-01
banana 2015-02-15 2.222e+00
coconut 2015-03-15 3.333e+01
durian 2015-04-15 4.444e+02
grp_b
NA 2015-05-15 5.550e+03
fig 2015-06-15 NA
grapefruit NA 7.770e+05
honeydew 2015-08-15 8.880e+06
len 8.00

Created on 2020-04-13 by the reprex package (v0.3.0)

But when groups = T, no summary is produced:

library(tidyverse)
library(gt)
exibble %>% select(group, char, date, num) %>% 
  gt(groupname_col = "group") %>%
  summary_rows(
    groups = T,
    columns = vars(group),
    fns = list(len = ~length(.)
    ))
char date num
grp_a
apricot 2015-01-15 1.111e-01
banana 2015-02-15 2.222e+00
coconut 2015-03-15 3.333e+01
durian 2015-04-15 4.444e+02
grp_b
NA 2015-05-15 5.550e+03
fig 2015-06-15 NA
grapefruit NA 7.770e+05
honeydew 2015-08-15 8.880e+06

Created on 2020-04-13 by the reprex package (v0.3.0)

It looks like there is a bug where the summary rows don't get built if there is no stub. I'll file an issue shortly to ensure this gets fixed. As a temporary workaround, this should work:

library(tidyverse)
library(gt)

exibble %>% 
  select(group, char, date, num) %>% 
  mutate(stub = rep(" ", nrow(.))) %>%
  gt(groupname_col = "group", rowname_col = "stub") %>%
  summary_rows(
    groups = TRUE,
    columns = vars(num),
    fns = list(len = ~length(.)
    )
  )

That creates a column with space characters before using gt(), then that stub column is specified in the gt() call.

No, I tried that:

library(tidyverse)
library(gt)
exibble %>% select(group, char, date, num) %>% 
  gt(groupname_col = "group") %>%
  summary_rows(
    groups = T,
    columns = vars(num),
    fns = list(len = ~length(.)
    ))
char date num
grp_a
apricot 2015-01-15 1.111e-01
banana 2015-02-15 2.222e+00
coconut 2015-03-15 3.333e+01
durian 2015-04-15 4.444e+02
grp_b
NA 2015-05-15 5.550e+03
fig 2015-06-15 NA
grapefruit NA 7.770e+05
honeydew 2015-08-15 8.880e+06

Created on 2020-04-13 by the reprex package (v0.3.0)