Home > Mobile >  Problems using only fileInput on Shiny
Problems using only fileInput on Shiny

Time:10-22

I'm inserting two codes: the first code works very well, but my database is mentioned in the code. However, I have this database in Excel and I'm trying to use it only by fileInput (second code). Unfortunately it's not working, the table that was supposed to be shown isn't working. Could you help me solve this problem?? Thank you very much!

To make it easier, I'm providing the excel database I'm using. https://syr.us/rVo

First code:

library(shiny)
library(shinythemes)
library(dplyr)
library(tidyverse)
library(lubridate)
library(readxl)
library(DT)
 
  
function.test<-function(){
    
    Test <- structure(list(date2 = structure(c(18808, 18808, 18809, 18810
    ), class = "Date"), Category = c("FDE", "ABC", "FDE", "ABC"), 
    coef = c(4, 1, 6, 1)), row.names = c(NA, 4L), class = "data.frame")

    return(Test)

  }
  

ui <- fluidPage(
  
  shiny::navbarPage(theme = shinytheme("flatly"), collapsible = TRUE,
                    br(),
                    tabPanel("",
                             sidebarLayout(
                               sidebarPanel(
                                 uiOutput('fileInput'),
                                 uiOutput('daterange')
                               
                               ),
                               mainPanel(
                                 dataTableOutput('table')

                               )
                             ))
  ))

server <- function(input, output,session) {
  

  data <- reactive(function.test())
  

  output$daterange <- renderUI({
    dateRangeInput("daterange1", "Period you want to see:",
                   min = min(data()$date2),
                   max = max(data()$date2))
  })
  
  data_subset <- reactive({
    req(input$daterange1)
    req(input$daterange1[1] <= input$daterange1[2])
    days <- seq(input$daterange1[1], input$daterange1[2], by = 'day')
    showModal(modalDialog("Wait", footer=NULL))
    on.exit(removeModal())
    All<- subset(data(), date2 %in% days)
    All<-All%>% mutate(TOTAL = rowSums(across(3:last_col()), na.rm = TRUE))
  })
  
  output$table <- renderDataTable({
   datatable(data_subset(),options = list( columnDefs = list(
          list(className = 'dt-center', targets = "_all")),
        paging = TRUE,  searching = FALSE,pageLength = 10,dom = 'tip',  scrollx=TRUE),    rownames = FALSE) %>%
      formatRound(c(3:4), digits=0)
  })
  
}

shinyApp(ui = ui, server = server) 

Second code:

library(shiny)
library(shinythemes)
library(dplyr)
library(tidyverse)
library(lubridate)
library(readxl)
library(DT)
 
  
function.test<-function(){
    
    return(Test)

  }
  

ui <- fluidPage(
  
  shiny::navbarPage(theme = shinytheme("flatly"), collapsible = TRUE,
                    br(),
                    tabPanel("",
                             sidebarLayout(
                               sidebarPanel(
                                 uiOutput('fileInput'),
                                 uiOutput('daterange')
                               
                               ),
                               mainPanel(
                                 dataTableOutput('table')

                               )
                             ))
  ))

server <- function(input, output,session) {
  
  data <- reactive(function.test())
  
  data <- eventReactive(input$file, {
    if (is.null(input$file)) {
      return(NULL)
    }
    else {
      df <- read_excel(input$file$datapath)
      return(df)
    }
 })
  
  output$fileInput <- renderUI({
    fileInput("file",h4("Import file"),
             multiple = T,accept = ".xlsx",
              placeholder = "No file selected")
  })
  

  output$daterange <- renderUI({
    dateRangeInput("daterange1", "Period you want to see:",
                   min = min(data()$date2),
                   max = max(data()$date2))
  })
  
  data_subset <- reactive({
    req(input$daterange1)
    req(input$daterange1[1] <= input$daterange1[2])
    days <- seq(input$daterange1[1], input$daterange1[2], by = 'day')
    showModal(modalDialog("Wait", footer=NULL))
    on.exit(removeModal())
    All<- subset(data(), date2 %in% days)
    All<-All%>% mutate(TOTAL = rowSums(across(3:last_col()), na.rm = TRUE))
  })
  
  output$table <- renderDataTable({
   datatable(data_subset(),options = list( columnDefs = list(
          list(className = 'dt-center', targets = "_all")),
        paging = TRUE,  searching = FALSE,pageLength = 10,dom = 'tip',  scrollx=TRUE),    rownames = FALSE) %>%
      formatRound(c(3:4), digits=0)
  })
  
}

shinyApp(ui = ui, server = server)

CodePudding user response:

Try this

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

return_coef <- function(df1, dmda, CategoryChosse) {
  
  x<-df1 %>% dplyr::select(starts_with("DR0"))
  
  x <- cbind(df1, setNames(df1$DR1 - x, paste0(names(x), "_PV")))
  PV <- dplyr::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 %>%
    dplyr::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"))
  
  SPV <- SPV %>%
    dplyr::filter(date2 == dmda, Category == CategoryChosse) %>%
    dplyr::select(-any_of(dropnames))
  
  if(length(grep("DR0", names(SPV))) == 0) {
    SPV[head(mat1,10)] <- NA_real_
  }
  
  datas <-SPV %>%
    dplyr::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("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) %>%
    dplyr::summarize(across(starts_with("DR1"), mean))
  
  m<-subset(m, Week == df1$Week[match(ymd(dmda), ymd(df1$date2))] & Category == CategoryChosse)$DR1
  
  
  if (nrow(datas)<=2){
    return (as.numeric(m))
  }
  
  else if(any(table(datas$Numbers) >= 3) & length(unique(datas$Numbers)) == 1){
    yz <- unique(datas$Numbers)
    return(as.numeric(yz))
    
  }
  
  else{
    mod <- nls(Numbers ~ b1*Days^2 b2,start = list(b1 = 0,b2 = 0),data = datas, algorithm = "port")
    return(as.numeric(coef(mod)[2]))
  }
  
}

ui <- fluidPage(
  
  shiny::navbarPage(theme = shinytheme("flatly"), collapsible = TRUE,
                    br(),
                    tabPanel("",
                             sidebarLayout(
                               sidebarPanel(
                                 uiOutput('fileInput'),
                                 uiOutput('daterange')
                                 
                               ),
                               mainPanel(
                                 dataTableOutput('table')
                               )
                             ))
  ))

server <- function(input, output,session) {
  
  output$fileInput <- renderUI({
    fileInput("file",h4("Import file"), multiple = T, accept = ".xlsx")
  })
  
  data <- eventReactive(input$file, {
    if (is.null(input$file)) {
      return(NULL)
    }
    else {
      df3 <- read_excel(input$file$datapath)
      validate(need(all(c('date1', 'date2') %in% colnames(df3)), "Incorrect file"))
      df4 <- df3 %>% mutate_if(~inherits(., what = "POSIXct"), as.Date) # Change POSIXct variables to Date class
      return(df4)
    }
  })
  
  output$daterange <- renderUI({
    req(data())
    dateRangeInput("daterange1", "Period you want to see:",
                   min = min(data()$date2),
                   max = max(data()$date2))
  })
  
  data_subset <- reactive({
    req(input$daterange1, data())
    req(input$daterange1[1] <= input$daterange1[2])
    days <- seq(input$daterange1[1], input$daterange1[2], by = 'day')
    df1 <- subset(data(), as.Date(date2) %in% days)
    df2 <- df1 %>% dplyr::select(date2,Category)
    Test <- cbind(df2, coef = apply(df2, 1, function(x) {return_coef(df1,x[1],x[2])}))
    Test
  })
  
  output$table <- renderDataTable({
    data_subset()
  })
  
}

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