Filter data table based on unique rows in Shiny?

Here's a minimal reprex of a simple data table in my Shiny app:

library(shiny)
library(DT)

shinyApp(
  ui <- fluidPage(
    DT::dataTableOutput("data")
  ),
  
  server <- function(input, output) {

    df <- reactiveValues(data = data.frame(
      
      Category = c('animal', 'plant', 'plant', 'car', 'car', 'drink', 'food'),
      Description = c("dog","rose","lilly","mercedes","honda","cola","burger"),
      stringsAsFactors = FALSE
    ))
    
    
    output$data <- DT::renderDataTable(
      df$data, server = FALSE, escape = FALSE, selection = 'none'
    )

    })
  })

Is there some way I can add a button to show only unique values in the "category" column?

The question of which row to keep does not matter here.

So can I add some button to make the resulting (unique) table with the following 5 variables?

  • animal
  • plant
  • car
  • drink
  • food

Thanks!

library(shiny)
library(DT)
library(dplyr)
shinyApp(
  ui <- fluidPage(
    radioButtons("unique_choice",
                 "unique category ? ",
                 choices=c("No","Yes"),
                 selected = "No"),
    DT::dataTableOutput("data")
  ),
  
  server <- function(input, output) {
    
    df <- reactiveValues(data = data.frame(
      
      Category = c('animal', 'plant', 'plant', 'car', 'car', 'drink', 'food'),
      Description = c("dog","rose","lilly","mercedes","honda","cola","burger"),
      stringsAsFactors = FALSE
    ))
    
    
    processed_data <- reactive({
      uc <- req(input$unique_choice)
      dfd <- req(df$data)
      val <- dfd
      if(uc=="Yes"){
        val <- dfd %>% group_by(Category) %>% mutate(rn=row_number()) %>%
          filter(rn==1) %>% ungroup()
      }
      val
    })
    output$data <- DT::renderDataTable(
      req(processed_data()), server = FALSE, escape = FALSE, selection = 'none'
    )
  })

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.