glin / reactable

Interactive data tables for R
https://glin.github.io/reactable
Other
627 stars 80 forks source link

Expandable rows within expandable rows #284

Closed schmid07 closed 1 year ago

schmid07 commented 1 year ago

My expectation for the below code was first that the main table would show the year column with three values (2007, 2008, and 2009). When clicking on the first set of expandable rows, the sub table would show each of the three species for each year. This part of the code works. For the 2nd set of expandable rows, however, I wasn't able to get the code to work as intended. I was hoping to show more info for each species for a given year. However, when I click the expandable row for 2007, then click the expandable row for the Adelie species, it shows information for 2008 and 2009 as well. Not sure how to fix this so that it would only show information for the given year and species selected.

Thanks in advance. Great work on reactable -- really enjoy using it!

library(palmerpenguins)
library(tidyverse)
library(reactable)

df_palmer <- palmerpenguins::penguins

df_main <- df_palmer  %>% 
  distinct(year)

df_sub_table_1 <- df_palmer %>% 
  distinct(species, year)

df_sub_table_2 <- df_palmer

reactable(df_main,
  details = function(index) {
    df_sub <-
      df_sub_table_1[df_sub_table_1$year ==
        df_main$year[index], ]
      reactable(df_sub,
                details = function(index2) {
                  df_sub_2 <- 
                    df_sub_table_2[df_sub_table_2$species == 
                                     df_sub_table_1$species[index2], ]
                  reactable(df_sub_2)
                })})
glin commented 1 year ago

In your most nested table details, I think replacing df_sub_table_1$species[index2] with df_sub$species[index2] will fix it (and then adding a filter on year). When you're indexing a data frame using the details function's index, that data frame should be the same data frame that was passed to reactable().

But also, I think what would help a lot would be to use more specifically-named variables since this is a pretty extreme level of nesting. I had to rewrite this a bit to understand it at first :). Here is what I had come up with:

library(palmerpenguins)
library(tidyverse)
library(reactable)

df_palmer <- palmerpenguins::penguins

df_years <- df_palmer %>% 
  distinct(year)

df_species_year <- df_palmer %>% 
  distinct(species, year)

reactable(
  df_years,
  details = function(index) {
    year <- df_years$year[index]
    df_sub_year <- df_species_year[df_species_year$year == year, ]
    reactable(
      df_sub_year,
      details = function(index2) {
        species <- df_sub_year$species[index2]
        df_sub_species_year <- df_palmer[df_palmer$species == species & df_palmer$year == year, ]
        reactable(df_sub_species_year)
      }
    )
  }
)
schmid07 commented 1 year ago

That works, thanks for taking a look!