RxT
RxT

Reputation: 548

Why my filter() with ifelse is not working?

I have a data.frame with the column "identificador_matriz_filial" filled with 1 and 2.

The user can select 3 options: Matriz (1), Filial (2) or Todos (3) to plot a graph. If the user select 3, the graph will show both 1 AND 2 (all data). Otherwise, will show 1 OR 2.

But I'm failing.

My UI


                box(plotOutput("regiao_plot"), widht = 8), 
                box(selectInput("regiao", "Região:", 
                                choices = list("Estado" = "uf", "Região" = "regiao"),
                                selected = "Estado")),
                box(selectInput("estab", "Estabelecimento:", 
                                choices = list("Todos" = 3, "Matriz" = 1, "Filial" = 2),
                                selected = "Todos"))

My SERVER


    output$regiao_plot <- renderPlot({
      
      col <- sym(input$regiao)
      mef <- as.numeric(input$estab)

      Coop_ativas %>% filter(identificador_matriz_filial %in% ifelse(mef %in% c(1,2),  mef, c(1:2))) %>%
                      select(!! col) %>% group_by(!! col) %>% count() %>% 
                      arrange(desc(n)) %>% head(10) %>% 
                      ggplot(aes(reorder(!! col, n), n), ) + 
                      geom_bar(stat="identity", fill="steelblue") +
                      geom_text(aes(label=n), vjust=0.5, hjust=-0.5, color="darkgrey", size=3) +
                      labs(title = "Cooperativas Ativas por Estado",
                           subtitle = "02/2020",
                           caption = "Fonte: RFB, tratado por OBSCOOP/USP",
                           #tag = "Figure 1",
                           x = "Estado",
                           y = "Quantidade") +
                      theme_minimal() + theme(plot.title = element_text(hjust = 0.5),
                                              plot.subtitle = element_text(hjust = 0.5),
                                              plot.caption = element_text(0.0)) +         
                      coord_flip() 


When the user select "Todos" (3), the graph shows 1. When the user select 1 or 2, the graph is plot right.

What am I missing?

Upvotes: 0

Views: 64

Answers (1)

YBS
YBS

Reputation: 21297

Replace

ifelse(mef %in% c(1,2),  mef, c(1:2))

with

(if (mef %in% c(1,2)) mef else c(1:2))

Upvotes: 1

Related Questions