【问题标题】:Problems using only fileInput on Shiny在 Shiny 上仅使用 fileInput 的问题
【发布时间】:2021-10-22 00:49:16
【问题描述】:

我正在插入两个代码:第一个代码运行良好,但代码中提到了我的数据库。但是,我在 Excel 中有这个数据库,我试图仅通过fileInput(第二个代码)使用它。不幸的是,它不起作用,应该显示的表格不起作用。你能帮我解决这个问题吗??非常感谢!

为了方便起见,我提供了我正在使用的 excel 数据库。 https://syr.us/rVo

第一个代码:

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) 

第二个代码:

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)

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    试试这个

    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) 
    

    【讨论】:

    • 感谢 YBS,但这是另一个代码。这个正在使用函数,并且代码中提到了数据库。我想通过fileInput,你知道如何调整吗?甚至可能是您在其中插入的这段代码,但我不想提及数据库,因为它仅适用于fileInput。在上面的示例中,我没有插入函数,因为我想减少代码以使其尽可能清晰。
    • YBS,谢谢,我会检查这段代码。 YBS,我们可以通过电子邮件或聊天交谈吗?
    • 谢谢YBS,我会做的,我觉得解释起来更容易。我已经得到了您的联系方式,我会尽快给您发送电子邮件。非常感谢! =)
    • 我给你发了一封电子邮件,请在可以的时候检查一下你是否收到了。谢谢 YBS!
    • 请尝试更新后的代码。
    猜你喜欢
    • 2018-02-17
    • 1970-01-01
    • 2018-08-26
    • 2015-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-27
    • 1970-01-01
    相关资源
    最近更新 更多