Robbie Voort
Robbie Voort

Reputation: 141

Use column with multiple variable as source for checkboxgroupinput

I am trying to create some sort of shiny app where you can select your allergens and see which foods are still good for you to eat.

The dataset I use is enormous but to give you an idea:

ID          allergens
1           milk, soya, peanuts
2           almonds, soya, flour
3           milk, almonds, butter

Now I would like to use all the variables from column 'allergens' but with all the variables individually. So when you open the shiny app the checkbox should contain either: 'milk' or 'soya'. At the moment it shows it as 'milk, soya, peanuts' or 'almonds, soya, flour' or 'milk, almonds butter'

So basically when I am allergic to milk, I would like the app to show all the products without milk (so it would only show ID 2 with all its extra details). At the moment all of the variables within the column allergens are , must I change this?

the code I use at the moment:

library(shiny)
library(ggplot2)
library(DT)

ui <- fluidPage(
  titlePanel("Basic DataTable"),
  
  # Create a new Row in the UI for selectInputs
  fluidRow(
    column(4,
           checkboxGroupInput("allergies",
                       "select allergies:",
                       c("All",
                         unique(as.character(food$allergens))))
    ),

  # Create a new row for the table.
  DT::dataTableOutput("table")
))

server <- function(input, output) {
  
  # Filter data based on selections
  output$table <- DT::renderDataTable(DT::datatable({
    data <- food
    if (input$allergies != "All") {
      data <- data[data$allergies == input$allergies,]
    }
    data
  }))
  
}

# Run the application 
shinyApp(ui = ui, server = server)

Upvotes: 0

Views: 34

Answers (1)

MattW
MattW

Reputation: 206

You can keep the info stored with commas and manipulate it as needed.

Split the strings using:

strsplit(food$allergens, ", ")

Then to get a vector of unique items, you'll need to unlist those:

unique(unlist(strsplit(food$allergens, ", ")))

Upvotes: 1

Related Questions