Home > Back-end >  Problem filtering data from database to run on Shiny
Problem filtering data from database to run on Shiny

Time:12-24

I'm having doubts about a filter I made. Note that I inserted in the function Test %>% filter(Filt != 0), in this case the ABC category was not supposed to appear. However, if you test the shiny code below, you will see the ABC option appear. See the image below. What am I doing wrong?

library(shiny)
library(shinythemes)
library(dplyr)
library(tidyverse)
library(lubridate)

df1<- structure(
  list(date1= c("2021-06-28","2021-06-28"),
       date2 = c("2021-07-01","2021-07-01"),
       Category = c("FDE","ABC"),
       Week= c("Friday","Monday"),
       Filt= c("1","0"),
       DR1 = c(14,11),
       DR01 = c(14,12), DR02= c(14,12),DR03= c(19,15),
       DR04 = c(15,14),DR05 = c(15,14),
       DR06 = c(12,14)),
  class = "data.frame", row.names = c(NA, -2L))


f1 <- function(df1, dmda, CategoryChosse, var1, var2, gnum=0) {
  
  df1 %>% filter(Filt != 0)
  
  x<-df1 %>% select(starts_with("DR0"))
  
  x<-cbind(df1, setNames(df1$DR1 - x, paste0(names(x), "_PV")))
  PV<-select(x, date2,Week, Category, DR1, ends_with("PV"))
  
  med<-PV %>%
    group_by(Category,Week) %>%
    dplyr::summarize(across(ends_with("PV"), median))
  
  SPV<-df1%>%
    inner_join(med, by = c('Category', 'Week')) %>%
    mutate(across(matches("^DR0\\d $"), ~.x  
                    get(paste0(cur_column(), '_PV')),
                  .names = '{col}_{col}_PV')) %>%
    dplyr::select(date1:Category, DR01_DR01_PV:last_col())
  
  SPV<-data.frame(SPV)
  
  mat1 <- df1 %>%
    filter(date2 == dmda, Category == CategoryChosse) %>%
    dplyr::select(starts_with("DR0")) %>%
    pivot_longer(cols = everything()) %>%
    arrange(desc(row_number())) %>%
    mutate(cs = cumsum(value)) %>%
    dplyr::filter(cs == 0) %>%
    pull(name)
  
  (dropnames <- paste0(mat1,"_",mat1, "_PV"))
  
  datas<-SPV %>%
    filter(date2 == ymd(dmda)) %>%
    group_by(Category) %>%
    dplyr::summarize(across(starts_with("DR0"), sum)) %>%
    pivot_longer(cols= -Category, names_pattern = "DR0(. )", values_to = "val") %>%
    mutate(name = readr::parse_number(name))
  colnames(datas)[-1]<-c(var1,var2)
  datas$days <- datas[[as.name(var1)]]
  datas$numbers <- datas[[as.name(var2)]]
  
  if(as.Date(dmda) < min(as.Date(df1$date1))){
    datas <- datas %>%
      group_by(Category) %>%
      slice(1:max(days) 1) %>%
      ungroup
  }else{
    datas <- datas %>%
      group_by(Category) %>%
      slice((as.Date(dmda) - min(as.Date(df1$date1) [
        df1$Category == first(Category)])):max(days) 1) %>%
      ungroup
  }
  
  maxrange <-  range(0, datas$numbers, na.rm = TRUE)
  maxrange[2] <- maxrange[2]   10 
  if (gnum) maxrange[2] <- maxrange[2]   40 
  max<-max(0, datas$days, na.rm = TRUE) 1
  limx = c(0,max)
  limy = c(0,maxrange[2])
  
  plot(numbers ~ days,  xlim= limx, ylim= limy, xlab = var1, ylab=var2,
       xaxs='i',data = datas,main = paste0(dmda, "-", CategoryChosse))
  
  model <- nls(numbers ~ b1*days^2 b2,start = list(b1 = 0,b2 = 0),data = datas, algorithm = "port")
  
  new.data <- data.frame(days = with(datas, seq(min(days),max(days),len = 45)))
  new.data <- rbind(0, new.data)
  lines(new.data$days,predict(model,newdata = new.data),lwd=2)
  coef_val<-coef(model)[2]
  points(0, coef_val, col="red",pch=19,cex = 2,xpd=TRUE)
}


ui <- fluidPage(
  
  ui <- shiny::navbarPage(theme = shinytheme("flatly"), collapsible = TRUE,
                          br(),
                          
                          tabPanel("",
                                   sidebarLayout(
                                     sidebarPanel(
                                       
                                       uiOutput("date"),
                                       uiOutput("mycode"),
                                     ),
                                     
                                     mainPanel(
                                       tabsetPanel(
                                         tabPanel("Graph1", plotOutput("graph",width = "100%", height = "600"))
                                       )
                                     )
                                   ))))


server <- function(input, output,session) {
  
  data <- reactive(df1)
  
  output$date <- renderUI({
    req(data())
    all_dates <- seq(as.Date('2021-01-01'), as.Date('2021-01-15'), by = "day")
    disabled <- as.Date(setdiff(all_dates, as.Date(data()$date2)), origin = "1970-01-01")
    dateInput(input = "date2",
              label = h4("Data"),
              min = min(data()$date2),
              max = max(data()$date2),
              value = min(data()$date2))
  })
  
  output$mycode <- renderUI({
    req(input$date2)
    df1 <- data()
    df2 <- df1[as.Date(df1$date2) %in% input$date2,]
    selectInput("code", label = h4("Category"),choices=unique(df2$Category))
  })
  
  output$graph <- renderPlot({
    req(input$date2,input$code)
    var1 = "Days"
    var2 = "Numbers"
    f1(data(),as.character(input$date2),as.character(input$code),var1,var2)
  })

}

shinyApp(ui = ui, server = server)

enter image description here

CodePudding user response:

Based on the updated code, the 'df1' passed to get the unique values of 'Category' is the original data

output$mycode <- renderUI({
    req(input$date2)
    df1 <- data() 
    df2 <- df1[as.Date(df1$date2) %in% input$date2,]
    selectInput("code", label = h4("Category"),choices=unique(df2$Category))
  })

instead, it would be

output$mycode <- renderUI({
    req(input$date2)
    df1 <- data() %>% 
          filter(Filt != 0)
    df2 <- df1[as.Date(df1$date2) %in% input$date2,]
    selectInput("code", label = h4("Category"),choices=unique(df2$Category))
  })

-full code

f1 <- function(df1, dmda, CategoryChosse, var1, var2, gnum=0) {
  
  df1 <- df1 %>% filter(Filt != 0) # updated the 'df1'
  
  x<-df1 %>% dplyr::select(starts_with("DR0"))
  
  x<-cbind(df1, setNames(df1$DR1 - x, paste0(names(x), "_PV")))
  PV<-select(x, date2,Week, Category, DR1, ends_with("PV"))
  
  med<-PV %>%
    group_by(Category,Week) %>%
    dplyr::summarize(across(ends_with("PV"), median))
  
  SPV<-df1%>%
    inner_join(med, by = c('Category', 'Week')) %>%
    mutate(across(matches("^DR0\\d $"), ~.x  
                    get(paste0(cur_column(), '_PV')),
                  .names = '{col}_{col}_PV')) %>%
    dplyr::select(date1:Category, DR01_DR01_PV:last_col())
  
  SPV<-data.frame(SPV)
  
  mat1 <- df1 %>%
    filter(date2 == dmda, Category == CategoryChosse) %>%
    dplyr::select(starts_with("DR0")) %>%
    pivot_longer(cols = everything()) %>%
    arrange(desc(row_number())) %>%
    mutate(cs = cumsum(value)) %>%
    dplyr::filter(cs == 0) %>%
    pull(name)
  
  (dropnames <- paste0(mat1,"_",mat1, "_PV"))
  
  datas<-SPV %>%
    filter(date2 == ymd(dmda)) %>%
    group_by(Category) %>%
    dplyr::summarize(across(starts_with("DR0"), sum)) %>%
    pivot_longer(cols= -Category, names_pattern = "DR0(. )", values_to = "val") %>%
    mutate(name = readr::parse_number(name))
  colnames(datas)[-1]<-c(var1,var2)
  datas$days <- datas[[as.name(var1)]]
  datas$numbers <- datas[[as.name(var2)]]
  
  if(as.Date(dmda) < min(as.Date(df1$date1))){
    datas <- datas %>%
      group_by(Category) %>%
      slice(1:max(days) 1) %>%
      ungroup
  }else{
    datas <- datas %>%
      group_by(Category) %>%
      slice((as.Date(dmda) - min(as.Date(df1$date1) [
        df1$Category == first(Category)])):max(days) 1) %>%
      ungroup
  }
  
  maxrange <-  range(0, datas$numbers, na.rm = TRUE)
  maxrange[2] <- maxrange[2]   10 
  if (gnum) maxrange[2] <- maxrange[2]   40 
  max<-max(0, datas$days, na.rm = TRUE) 1
  limx = c(0,max)
  limy = c(0,maxrange[2])
  
  plot(numbers ~ days,  xlim= limx, ylim= limy, xlab = var1, ylab=var2,
       xaxs='i',data = datas,main = paste0(dmda, "-", CategoryChosse))
  
  model <- nls(numbers ~ b1*days^2 b2,start = list(b1 = 0,b2 = 0),data = datas, algorithm = "port")
  
  new.data <- data.frame(days = with(datas, seq(min(days),max(days),len = 45)))
  new.data <- rbind(0, new.data)
  lines(new.data$days,predict(model,newdata = new.data),lwd=2)
  coef_val<-coef(model)[2]
  points(0, coef_val, col="red",pch=19,cex = 2,xpd=TRUE)
}


ui <- fluidPage(
  
 shiny::navbarPage(theme = shinytheme("flatly"), collapsible = TRUE,
                          br(),
                          
                          tabPanel("",
                                   sidebarLayout(
                                     sidebarPanel(
                                       
                                       uiOutput("date"),
                                       uiOutput("mycode"),
                                     ),
                                     
                                     mainPanel(
                                       tabsetPanel(
                                         tabPanel("Graph1", plotOutput("graph",width = "100%", height = "600"))
                                       )
                                     )
                                   ))))


server <- function(input, output,session) {
  
  data <- reactive(df1)
  
  output$date <- renderUI({
    req(data())
    all_dates <- seq(as.Date('2021-01-01'), as.Date('2021-01-15'), by = "day")
    disabled <- as.Date(setdiff(all_dates, as.Date(data()$date2)), origin = "1970-01-01")
    dateInput(input = "date2",
              label = h4("Data"),
              min = min(data()$date2),
              max = max(data()$date2),
              value = min(data()$date2))
  })
  
  output$mycode <- renderUI({
    req(input$date2)
    df1 <- data() %>% 
          filter(Filt != 0)
    df2 <- df1[as.Date(df1$date2) %in% input$date2,]
    selectInput("code", label = h4("Category"),choices=unique(df2$Category))
  })
  
  output$graph <- renderPlot({
    req(input$date2,input$code)
    var1 = "Days"
    var2 = "Numbers"
    f1(data(),as.character(input$date2),as.character(input$code),var1,var2)
  })
  
}

shinyApp(ui = ui, server = server)

-output

enter image description here

  • Related