调整Shiny代码使函数生成Test数据集的第二段代码正常展示运行结果
Shiny代码修复方案
核心错误点
- 函数逻辑嵌套错误:将Test数据集生成代码写在了计算单个coef值的
return_coef函数内部,导致调用时递归死循环,无法正常输出结果 - 函数返回值不符合要求:
function.test当前仅返回原始数据df1,没有生成与第一段代码结构一致、带coef列的Test数据集 - 日期格式不匹配:df1中的date2列为字符类型,未转为Date类型,无法正常用于日期范围筛选逻辑
- 正则表达式转义错误:
matches("^DR0\d+$")缺少转义符,R中需写为matches("^DR0\\d+$")才能正确匹配列名 - 分组汇总未关闭分组:dplyr的summarize操作后未添加
.groups = "drop"参数,会导致后续计算出现分组冲突警告
修复后完整代码
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","2021-06-28"), date2 = c("2021-06-30","2021-06-30","2021-07-01","2021-07-02"), Category = c("FDE","ABC","FDE","ABC"), Week= c("Wednesday","Wednesday","Friday","Friday"), DR1 = c(4,1,6,1), DR01 = c(4,1,4,4), DR02= c(4,2,6,0),DR03= c(9,5,4,0), DR04 = c(5,4,3,5),DR05 = c(5,4,5,0), DR06 = c(2,4,3,5),DR07 = c(2,5,4,0), DR08 = c(3,4,5,0),DR09 = c(2,3,4,0)), class = "data.frame", row.names = c(NA, -4L)) # 转换日期格式为Date类型 df1$date1 <- ymd(df1$date1) df1$date2 <- ymd(df1$date2) # 定义coef计算函数,仅返回单个计算结果 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), .groups = "drop") 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)) datas<-SPV %>% filter(date2 == ymd(dmda)) %>% group_by(Category) %>% summarize(across(starts_with("DR0"), sum), .groups = "drop") %>% 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 mod <- nls(Numbers ~ b1*Days^2+b2,start = list(b1 = 0,b2 = 0),data = datas, algorithm = "port") # 仅返回计算得到的coef值 return(as.numeric(coef(mod)[2])) } # 批量计算所有行的coef值,生成与第一段代码结构一致的Test数据集 Test <- cbind(df1 %>% select(date2,Category), coef = mapply(function(d, c) return_coef(df1, d, c), df1$date2, df1$Category)) return(Test) } ui <- fluidPage( shiny::navbarPage(theme = shinytheme("flatly"), collapsible = TRUE, br(), tabPanel("", sidebarLayout( sidebarPanel( uiOutput('daterange'), br() ), mainPanel( dataTableOutput('table'), br(), br(), downloadButton("dl", "Download") ), )) )) server <- function(input, output,session) { data <- reactive(function.test()) data_subset <- reactive({ req(input$daterange1) days <- seq(input$daterange1[1], input$daterange1[2], by = 'day') subset(data(), date2 %in% days) }) output$daterange <- renderUI({ dateRangeInput("daterange1", "Period you want to see:", start = min(data()$date2), end = max(data()$date2)) }) output$table <- renderDataTable({ data_subset() }) output$dl <- downloadHandler( filename = function() { "data.xlsx"}, content = function(file) { writexl::write_xlsx(data_subset(), path = file) } ) } shinyApp(ui = ui, server = server)
内容的提问来源于stack exchange,提问作者Antonio
相关产品推荐
相关产品推荐

