Реактивные функции для 2 фильтров - PullRequest
0 голосов
/ 21 сентября 2019

Я пытался с кодом во Flexdashboard, и он работает частично.Здесь есть 3 фильтра для Производительность , Класс и Семейство продуктов :

  1. Когда Производительность равна«Сюжет», Класс - это «Все», а Семейство продуктов - это «Все», график отображается, и он идеально подходит.
  2. Когда Производительность - это «График», Класс - это «А», а Семейство продуктов пусто, график отображается и он идеален.
  3. Но когда Производительность - это «График», Класс - это «А», а Семейство продуктов - это «Семейство продуктов 1», график не отображается для Семейства продуктов 1, вместо этого имеетсязаговор для всех трех семейств.

В основном мне нужно, чтобы эти фильтры использовались как мое желаниеЕсть ли способ сделать вышеупомянутую вещь?

---
title: "ABC INC"
runtime: shiny
output: 
  flexdashboard::flex_dashboard:
  orientation: rows
vertical_layout: scroll
source_code: embed
theme: cosmo
---

```{r setup, include=FALSE}
library(flexdashboard)
library(readxl)
library(tidyverse)
library(ggplot2)
library(plotly)
library(reshape)
```
```{r}
df <- structure(list(Class = c("A", "A", "A", "A", "A", "B", "B", "B", "B", "B"),
                     Product = c("Product 1", "Product 2", "Product 3", "Product 4", "Product 5", "Product 1", "Product 2", "Product 3", "Product 4", "Product 5"), 
                    `Product Family` = c("Product Family 1", "Product Family 1", "Product Family 1", "Product Family 2", "Product Family 3", "Product Family 1", "Product Family 1", "Product Family 1", "Product Family 2", "Product Family 3"), 
                    `Month Ending Date` = structure(c(1420070400, 1422748800, 1425168000, 1427846400, 1430438400, 1420070400, 1422748800, 1425168000, 1427846400, 1430438400), 
                                                    class = c("POSIXct", "POSIXt"), tzone = "UTC"), 
                     Spend = c(95, 93, 98, 100, 93, 95, 93, 98, 100, 93)), 
                row.names = c(NA, -10L), 
                class = c("tbl_df", "tbl", "data.frame"))

df <- as.data.frame(df)
colnames(df) <- gsub(" ","_",colnames(df))
df$Month_Ending_Date <- as.Date(df$Month_Ending_Date)
```

Performance
=======================

  Filters {.sidebar}
------------------

  ```{r}
selectInput("Plot",h5("Performance"), choices = c("","Plot"))
selectInput("Class",h5("Class"), choices = c("All",levels(factor(df$Class))), multiple = TRUE)
selectInput("ProductFamily",h5("Product Family"), choices = c("All",levels(factor(df$Product_Family))), multiple = TRUE)
```

Output
------------------

### Chart A {data-heigh=500}

```{r}
plotOutput("graph",height = "5000px",width = "1000px")
sel_data <- reactive({
    df[df$Class %in% input$Class | df$Product_Family %in% input$ProductFamily,]
})


graph <- reactive({
  if (input$Plot == "Plot" && input$Class == "All" && input$ProductFamily == "All") {
    ggplot(df,aes(x=Month_Ending_Date,y=Spend,color = Product)) + 
      geom_point()+facet_wrap("Product_Family") + theme(legend.position = "none") +
      theme(legend.position = "none")

  } else {
    ggplot(sel_data(),aes(x=Month_Ending_Date,y=Spend,color = Product)) +
      geom_point()+facet_wrap("Product_Family") + 
      theme(legend.position = "none") +
      geom_text(data = sel_data(), aes(x=Month_Ending_Date, label=round((Spend/1000000),2)),
                size=3,angle = 45, color = "black",vjust=-0.25)+theme(legend.position = "bottom")
  }
})
output$graph <- renderPlot({
  graph() 
})
 ```

1 Ответ

0 голосов
/ 21 сентября 2019

Рассмотрите возможность расширения sel_data() реактивной функции для всех возможных вариантов с обработкой пустых входов и "All" выборами:

sel_data <- reactive({
  # ADJUST INPUTS FOR ALL COLUMN FACTORS
  if(input$Class == "All" | is.na(input$Class) | is.null(input$Class)) 
    input$Class <- levels(factor(df$Class))
  if(input$Product_Family == "All" | is.na(input$Product_Family) | is.null(input$Product_Family)) 
    input$Product_Family <- levels(factor(df$Product_Family))

  # ALL POSSIBLE CHOICES
  choices_df <- expand.grid(Class = levels(factor(df$Class)),
                            Product_Family = levels(factor(df$Product_Family))
  )
  # SUBSET CHOICES TO INPUT VALUES
  sub_df <- with(choices_df, choices_df[Class %in% input$Class & 
                                        Product_Family %in% input$Product_Family,])

  # MERGE TO MAIN FOR FILTERED RECORDS
  merge(df, sub_df, by=c("Class", "Product_Family"))
})

Rextester demo

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...