You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shiny应用点击Download按钮仅导出Excel不生成图表的调整方法问询

R Shiny导出Excel时跳过绘图逻辑的调整方案

核心思路

把原代码中耦合了系数计算和绘图的return_coef函数拆分为两个独立函数:

  • 仅负责系数计算的calc_coef:无绘图逻辑,供导出Excel时调用,大幅降低大数据量下的导出耗时
  • 负责绘图展示的plot_coef:调用calc_coef获取系数后执行绘图逻辑,供前端页面绘图使用

具体修改内容

1. 替换原return_coef函数

删除原return_coef,替换为以下两个函数(已同步修正原代码中管道符缺失%的语法错误):

# 仅计算系数,无绘图逻辑,供导出用
calc_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
  
  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])) 
  }
}

# 绘图函数,供前端页面调用
plot_coef <- function(df1, dmda, CategoryChosse) {
  # 先调用计算函数拿系数
  coef_val <- calc_coef(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")
  } 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")
  } 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")
  }
}

2. 修改服务端中绘图的调用逻辑

把原output$graph中的return_coef替换为plot_coef:

output$graph <- renderPlot({
  req(input$date2,input$code)
  plot_coef(data(),as.character(input$date2),as.character(input$code))
})

3. 修改导出数据计算的调用逻辑

把原data_subset中的return_coef替换为calc_coef:

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) {calc_coef(data(),x[1],x[2])}))
  Test
})

效果说明

调整后点击Download按钮时,只会调用无绘图逻辑的calc_coef计算系数,不会执行任何绘图操作,大数据量下的导出耗时会大幅降低,同时前端的绘图展示功能不受任何影响。


内容的提问来源于stack exchange,提问作者Antonio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 15:36:03