Home > Blockchain >  Press download and just generate the excel without the need to plot the graphs
Press download and just generate the excel without the need to plot the graphs

Time:10-18

The code below generates a graphs for 01/07, 02/07 and 04/07. If you see in the graph there is a value, which are the values I get in my function. If I press Download, I can download a spreadsheet with these values. Everything is OK so far. What I want to try to adjust is the following, if I press Download, I noticed that the graphs corresponding to the dates are also plotted, since the returns are in the if and else condiction. As this is a small base, it goes fast, however, if I have a large base, it takes time, because in addition to taking the coefficient value, it generates the plots no need. How can I help this, that is, when I press the Download button, only download the spreadsheet with the coefficients, and the code doesn't need to make the plots.

Executable code below:

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

function.test<-function(){
  
  df1 <- structure(
    list(date1= c("2021-06-28","2021-06-28","2021-06-28"),
         date2 = c("2021-07-01","2021-07-02","2021-07-04"),
         Category = c("ABC","ABC","ABC"),
         Week= c("Wednesday","Wednesday","Wednesday"),
         DR1 = c(4,1,0),
         DR01 = c(4,1,0), DR02= c(4,2,0),DR03= c(9,5,0),
         DR04 = c(5,4,0),DR05 = c(5,4,0),DR06 = c(5,4,0),DR07 = c(5,4,0),DR08 = c(5,4,0)),
    class = "data.frame", row.names = c(NA, -3L))
  
  return(df1)
  
}

return_coef <- function(df1, dmda, CategoryChosse) {
  
  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) %>%
    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')) %>%
    select(date1:Category, DR01_DR01_PV:last_col())
  
  SPV<-data.frame(SPV)
  
  mat1 <- df1 %>%
    filter(date2 == dmda, Category == CategoryChosse) %>%
    select(starts_with("DR0")) %>%
    pivot_longer(cols = everything()) %>%
    arrange(desc(row_number())) %>%
    mutate(cs = cumsum(value)) %>%
    filter(cs == 0) %>%
    pull(name)
  
  (dropnames <- paste0(mat1,"_",mat1, "_PV"))
  
  SPV <- SPV %>%
    filter(date2 == dmda, Category == CategoryChosse) %>%
    select(-any_of(dropnames))
  
  if(length(grep("DR0", names(SPV))) == 0) {
    SPV[head(mat1,10)] <- NA_real_
  }
  
  datas <-SPV %>%
    filter(date2 == ymd(dmda)) %>%
    group_by(Category) %>%
    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("Days","Numbers")
  
  
  datas <- datas %>% 
    group_by(Category) %>% 
    slice((as.Date(dmda) - min(as.Date(df1$date1) [
      df1$Category == first(Category)])):max(Days) 1) %>%
    ungroup
  
  m<-df1 %>%
    group_by(Category,Week) %>%
    summarize(across(starts_with("DR1"), mean))
  
  m<-subset(m, Week == df1$Week[match(ymd(dmda), ymd(df1$date2))] & Category == CategoryChosse)$DR1
  
  maxrange <-  range(min(0, datas$Numbers, na.rm = TRUE), na.rm = TRUE)
  maxrange[1] <- maxrange[1] - (maxrange[1] %%10)   35
  
  max<-max(0, datas$Days, na.rm = TRUE) 1
  
  plot(Numbers ~ Days,  xlim= c(0,max),  ylim= c(0,maxrange[1]),
       xaxs='i',data = datas,main = paste0(dmda, "-", CategoryChosse))
  
  
  if (nrow(datas)<=2){
    abline(h=m,lwd=2) 
    points(0, m, col = "red", pch = 19, cex = 2, xpd = TRUE)
    text(.1,m  .5, round(m,1), cex=1.1,pos=4,offset =1,col="black")
    return (as.numeric(m))
  }
  
  else if(any(table(datas$Numbers) >= 3) & length(unique(datas$Numbers)) == 1){
    yz <- unique(datas$Numbers)
    lines(c(0,datas$Days), c(yz, datas$Numbers), lwd = 2)
    points(0, yz, col = "red", pch = 19, cex = 2, xpd = TRUE)
    text(.1,yz  .5,round(yz,1), cex=1.1,pos=4,offset =1,col="black")
    return(as.numeric(yz))}
    
  else{
    mod <- 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(mod,newdata = new.data),lwd=2)
    coef<-coef(mod)[1]
    points(0, coef, col="red",pch=19,cex = 2,xpd=TRUE)
    text(.99,coef   1,max(0, round(coef,1)), cex=1.1,pos=4,offset =1,col="black")
    return(as.numeric(coef(mod)[2])) }
  
    }



ui <- fluidPage(
  
  shiny::navbarPage(theme = shinytheme("flatly"), collapsible = TRUE,
                    br(),
                    tabPanel("",
                             sidebarLayout(
                               sidebarPanel(
                                 uiOutput("date"),
                                 uiOutput("mycode"),
                                 uiOutput('daterange'),
                                 br()
                                 
                               ),
                               mainPanel(
                                 #dataTableOutput('table'),
                                 plotOutput("graph",width = "100%", height = "600"),
                                 br(), br(),
                                 downloadButton("dl", "Download")
                               ),
                             ))
  ))

server <- function(input, output,session) {
  
  data <- reactive(function.test())
  

  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("Choose"),
              min = min(data()$date2),
              max = max(data()$date2),
              value = NA,
              datesdisabled = disabled)
    
  })
  

  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)
    return_coef(data(),as.character(input$date2),as.character(input$code))})
  

  
  output$table <- renderDataTable({
    data_subset()
  })
  
  
  data_subset <- reactive({
    req(input$daterange1)
    days <- seq(input$daterange1[1], input$daterange1[2], by = 'day')
    df1 <- subset(data(), as.Date(date2) %in% days)
    df2 <- df1 %>% select(date2,Category)
    Test <- cbind(df2, coef = apply(df2, 1, function(x) {return_coef(data(),x[1],x[2])}))
    Test
  })
  
  output$daterange <- renderUI({
    dateRangeInput("daterange1", "Period you want to see:",
                   start = min(data()$date2),
                   end   = max(data()$date2))
  })
  

  output$dl <- downloadHandler(
    filename = function() { "data.xlsx"},
    content = function(file) {
      writexl::write_xlsx(data_subset(), path = file)
    }
  )
}

shinyApp(ui = ui, server = server) 

Example: I pressed Download, but graphs are plotted.

enter image description here

CodePudding user response:

Try this

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

function.test<-function(){
  
  df1 <- structure(
    list(date1= c("2021-06-28","2021-06-28","2021-06-28"),
         date2 = c("2021-07-01","2021-07-02","2021-07-04"),
         Category = c("ABC","ABC","ABC"),
         Week= c("Wednesday","Wednesday","Wednesday"),
         DR1 = c(4,1,0),
         DR01 = c(4,1,0), DR02= c(4,2,0),DR03= c(9,5,0),
         DR04 = c(5,4,0),DR05 = c(5,4,0),DR06 = c(5,4,0),DR07 = c(5,4,0),DR08 = c(5,4,0)),
    class = "data.frame", row.names = c(NA, -3L))
  
  return(df1)
  
}

return_coef <- function(df1, dmda, CategoryChosse) {
  
  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) %>%
    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')) %>%
    select(date1:Category, DR01_DR01_PV:last_col())
  
  SPV<-data.frame(SPV)
  
  mat1 <- df1 %>%
    filter(date2 == dmda, Category == CategoryChosse) %>%
    select(starts_with("DR0")) %>%
    pivot_longer(cols = everything()) %>%
    arrange(desc(row_number())) %>%
    mutate(cs = cumsum(value)) %>%
    filter(cs == 0) %>%
    pull(name)
  
  (dropnames <- paste0(mat1,"_",mat1, "_PV"))
  
  SPV <- SPV %>%
    filter(date2 == dmda, Category == CategoryChosse) %>%
    select(-any_of(dropnames))
  
  if(length(grep("DR0", names(SPV))) == 0) {
    SPV[head(mat1,10)] <- NA_real_
  }
  
  datas <-SPV %>%
    filter(date2 == ymd(dmda)) %>%
    group_by(Category) %>%
    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("Days","Numbers")
  
  
  datas <- datas %>% 
    group_by(Category) %>% 
    slice((as.Date(dmda) - min(as.Date(df1$date1) [
      df1$Category == first(Category)])):max(Days) 1) %>%
    ungroup
  
  m<-df1 %>%
    group_by(Category,Week) %>%
    summarize(across(starts_with("DR1"), mean))
  
  m<-subset(m, Week == df1$Week[match(ymd(dmda), ymd(df1$date2))] & Category == CategoryChosse)$DR1
  
  maxrange <-  range(min(0, datas$Numbers, na.rm = TRUE), na.rm = TRUE)
  maxrange[1] <- maxrange[1] - (maxrange[1] %%10)   35
  
  max<-max(0, datas$Days, na.rm = TRUE) 1
  
  plot(Numbers ~ Days,  xlim= c(0,max),  ylim= c(0,maxrange[1]),
       xaxs='i',data = datas,main = paste0(dmda, "-", CategoryChosse))
  
  
  if (nrow(datas)<=2){
    abline(h=m,lwd=2) 
    points(0, m, col = "red", pch = 19, cex = 2, xpd = TRUE)
    text(.1,m  .5, round(m,1), cex=1.1,pos=4,offset =1,col="black")
    return (as.numeric(m))
  }
  
  else if(any(table(datas$Numbers) >= 3) & length(unique(datas$Numbers)) == 1){
    yz <- unique(datas$Numbers)
    lines(c(0,datas$Days), c(yz, datas$Numbers), lwd = 2)
    points(0, yz, col = "red", pch = 19, cex = 2, xpd = TRUE)
    text(.1,yz  .5,round(yz,1), cex=1.1,pos=4,offset =1,col="black")
    return(as.numeric(yz))}
  
  else{
    mod <- 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(mod,newdata = new.data),lwd=2)
    coef<-coef(mod)[1]
    points(0, coef, col="red",pch=19,cex = 2,xpd=TRUE)
    text(.99,coef   1,max(0, round(coef,1)), cex=1.1,pos=4,offset =1,col="black")
    return(as.numeric(coef(mod)[2])) }
  
}



ui <- fluidPage(
  
  shiny::navbarPage(theme = shinytheme("flatly"), collapsible = TRUE,
                    br(),
                    tabPanel("",
                             sidebarLayout(
                               sidebarPanel(
                                 uiOutput("date"),
                                 uiOutput("mycode"),
                                 uiOutput('daterange'),
                                 tags$style(".well {background-color:transparent;}"),
                                 br(),br(),br(), 
                                 conditionalPanel(condition = "output.mycode", 
                                                  actionBttn(inputId="plot", 
                                                             label="PLOT",
                                                             style = "simple",
                                                             color = "success",
                                                             size = "md",
                                                             block = FALSE,
                                                             no_outline = TRUE
                                                  ),
                                                  div(style="display: inline-block; width: 10px;",HTML("<br>")),
                                                  downloadButton("dl", "Download")
                                                  )
                                
                               ),
                               
                               mainPanel(
                                 #dataTableOutput('table'),
                                 plotOutput("graph",width = "100%", height = "600"),
                                 br()
                               ),
                             ))
  ))

server <- function(input, output,session) {
  
  data <- reactive(function.test())
  
  
  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("Choose"),
              min = min(data()$date2),
              max = max(data()$date2),
              value = NA,
              datesdisabled = disabled)
    
  })
  
  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))
  })
  
  observeEvent(input$plot, {
    output$graph <- renderPlot({
      req(input$date2,input$code)
      return_coef(data(),as.character(input$date2),as.character(input$code))
    })
  }, ignoreInit = TRUE)
  
  output$table <- renderDataTable({
    data_subset()
  })
  
  data_subset <- reactive({
    req(input$daterange1)
    days <- seq(input$daterange1[1], input$daterange1[2], by = 'day')
    df1 <- subset(data(), as.Date(date2) %in% days)
    df2 <- df1 %>% select(date2,Category)
    Test <- cbind(df2, coef = apply(df2, 1, function(x) {return_coef(data(),x[1],x[2])}))
    Test
  })
  
  output$daterange <- renderUI({
    dateRangeInput("daterange1", "Period you want to see:",
                   start = min(data()$date2),
                   end   = max(data()$date2))
  })
  
  
  output$dl <- downloadHandler(
    filename = function() { "data.xlsx"},
    content = function(file) {
      writexl::write_xlsx(data_subset(), path = file)
    }
  )
}

shinyApp(ui = ui, server = server) 
  • Related