Search code examples
rdatatableshinyflexdashboard

Filter table with action button and 2nd table with crosstalk


I have a flexdashboard with 1 input select, an action button and two tables. I want the first table to be filtered using the input select, triggered by the action button. Then I want to filter a 2nd table depending on a selected row from table 1. For the latter I'm thinking of using crosstalk.

This works (using the example from: stackoverflow.com/questions/48581598/filter-two-tables-with-crosstalk):

df1 <- structure(list(owner = structure(c(1L, 2L, 2L, 2L, 2L), .Label = c   ("John", "Mark"), class = "factor"), hp = c(250, 120, 250, 100, 110), car =    structure(c(2L, 2L, 2L, 1L, 1L), .Label = c("benz", "bmw"), class = "factor"),  id = structure(1:5, .Label = c("car1", "car2", "car3", "car4", "car5"), class = "factor")), .Names = c("owner", "hp", "car", "id"), row.names = c(NA, -5L), class = "data.frame")

df2 <- structure(list(car = structure(c(1L, 2L, 1L, 2L), .Label = c  ("benz","bmw"), class = "factor"), owner = structure(c(1L, 1L, 2L, 2L), .Label  = c("John", "Mark"), class = "factor"), freq = c(0L,1L, 2L, 2L)), .Names = c  ("car", "owner", "freq"), row.names = c(NA, -4L), class = "data.frame")

shared_df1 <- SharedData$new(df1, ~owner, group = "Choose owner")
shared_df2 <- SharedData$new(df2, ~owner, group = "Choose owner")

filter_select("owner", "Car owner:", shared_df1, ~owner)

DT::datatable(shared_df1)
DT::datatable(shared_df2)
#---------------------------

But adding this doesn't:

selectInput(inputId = 'owner', label = NULL, choices =c("All", "John", "Mark"), selected ="All")

actionButton("Find", "Find owner ")

observeEvent(input$Find,{
df1<-df1%>%filter(a==input$owner|input$owner=="All")
})

Please help


Solution

  • It's not exactly clear what you want to do with the second table. As for the first, you could try creating a reactive dataframe which returns the filtered dataframe:

    df1_filtered = reactive({
      if(input$owner != "All"){
        df1 %>% filter(owner == input$owner)
      } else {
        df1
      }
    })
    
    df2_filtered = reactive({
      if(condition for second table){
        # If you wanted to filter the second owners in the first df
        df2 %>% filter(owner %in% df1_filtered()$owner)
      } else {
        df2
      }
    })
    
    
    observeEvent(input$Find,{
      renderTable(df1_filtered())
    })
    

    But let me know what you are looking to do exactly and I can modify this. Also I'm not 100% sure the old if-else framework is best practices for reactive dataframes but it has worked well for me.