Is it possible to group-wise color every other row? #1321
Replies: 2 comments
-
I can't find a way to color by group within the natural library(tidyverse)
library(gt)
color_by_group = function(x, ...) {
x = x %>%
ungroup %>%
arrange(...)
myrows = x %>%
mutate(row.num = 1:n()) %>%
group_by(...) %>%
mutate(keep=1:n() %% 2 == 1) %>%
ungroup() %>%
filter(keep) %>%
pull(row.num)
group.col.names = enquos(...) %>% map_chr(as_label)
x %>%
gt(groupname_col = group.col.names) %>%
tab_style(
style = cell_fill(color = 'grey90'),
locations = list(
cells_body(rows = myrows)
)
)
}
set.seed(2)
dat = towny %>%
select(name, status, land_area_km2) %>%
slice_sample(n = 3, by = status)
dat %>%
color_by_group(status) mtcars %>%
slice(10:15) %>%
select(cyl, carb, mpg, hp) %>%
color_by_group(cyl, carb) |
Beta Was this translation helpful? Give feedback.
-
@eipi10 excellent function! On this note, targeting is pretty weak when groups are involved. I think there needs to be things like a |
Beta Was this translation helpful? Give feedback.
-
In this table I have colored every other row.
However, is it also possible to achieve every other row on a per-group basis? With the following code, the coloring is different for the different groups.
So in the desired row I'd like to see 'Nairn and Hyman' and 'Pelee' have a grey background. Is that possible?
Beta Was this translation helpful? Give feedback.
All reactions