Ad

Conditional Values Using If Else Within Shiny App Using Tidyverse And Dplyr To Group And Filter A Dataset

- 1 answer

I have a simple shiny that presents descriptive statistics using reactive. However, I would like to use ifelse within tidyverse pipe (and not writing tons of codes). However, I´m not being able to do that. I checked previous post but it´s not working as well. I imagine this part is close to what I want:

 students_results <- reactive({
    ds %>%
      
    if (input$all_quest == TRUE) {  do nothing here!! } else {  
      filter(domain == input$domain) %>%
        group_by(input$quest)
    }
    summarise(mean(test))

This code is 100% working,

library(shiny)
library(tidyverse)
library(DT)
ds <- data.frame(quest = c(2,4,6,8), domain = c("language", "motor"), test = rnorm(120, 10,1))

ui <- fluidPage(
  
  sidebarLayout(
    tabPanel("student",
             sidebarPanel(
               selectInput("domain", "domain", selected = "language", choices = c("language", "motor")),
               selectInput("quest", "Questionnaire", selected = "2", choices = unique(ds$quest)),
               checkboxInput("all_quest",
                             label = "Show all questionnaires",
                             value = FALSE)
             )
    ),
    
    mainPanel(
      dataTableOutput("table")
    )
  )
)
server <- function(input, output) {
  
  students_results <- reactive({
    if (input$all_quest == TRUE) {
      ds %>% 
        group_by(quest, domain) %>% 
        summarise(mean(test))
    } 
    else   {
      ds %>% 
        filter(domain == input$domain) %>%
        group_by(input$quest) %>% 
        summarise(mean(test))
      
    }
  })
  
  output$table <- renderDataTable({
    students_results()
  }
  )
}
shinyApp(ui = ui, server = server)
  • Please check the akrun response below. Everything is working.
Ad

Answer

We may need to use {} to block the code between the %>%

 students_results <- reactive({
    ds %>%
      {
        if (input$all_quest == TRUE) {
          . 
            } else {
          {.} %>%
           filter(domain == input$domain) %>%
           group_by(input$quest) 
       } 
        
        }%>%
    summarise(mean(test))
  })
Ad
source: stackoverflow.com
Ad