R 获取当前输入值列表时出现问题

R 获取当前输入值列表时出现问题,r,shiny,shiny-reactivity,R,Shiny,Shiny Reactivity,我在从几个CooConditionalPanel获取更新的值时遇到了很多问题。我创建了一个反应变量parList,它应该包含parN_sig输入变量。这些变量应该来自条件面板,它们都被命名为parN_sig。我不知道为什么,但当UI上显示另一个面板时,我总是从double_sig面板获取值。 这是我的密码: 用户界面 服务器.r 我最近开始使用Shiny,因此非常感谢您的帮助。提前谢谢 欢迎来到SO 您自己已经确定了问题:…都被命名为parN_sig。这意味着你没有几个输入,你只有一个。因此,无

我在从几个CooConditionalPanel获取更新的值时遇到了很多问题。我创建了一个反应变量parList,它应该包含parN_sig输入变量。这些变量应该来自条件面板,它们都被命名为parN_sig。我不知道为什么,但当UI上显示另一个面板时,我总是从double_sig面板获取值。 这是我的密码: 用户界面

服务器.r

我最近开始使用Shiny,因此非常感谢您的帮助。提前谢谢

欢迎来到SO

您自己已经确定了问题:…都被命名为parN_sig。这意味着你没有几个输入,你只有一个。因此,无论您试图访问哪个面板,您总是从第一个条件面板获得say input$par2_sig的值

您有两个选择:

为每个文本输入提供唯一的名称。那将是一种痛苦。或 使用模块。他们需要一点时间来适应,但最终还是值得努力的。 如果您正确设置模块,您将能够为每个条件面板使用相同的模块,即使它们具有不同数量的文本输入

有关创建第一个模块的帮助,请参阅

jscode <- "
shinyjs.disableTab = function(name) {
  var tab = $('.nav li a[data-value=' + name + ']');
  tab.bind('click.tab', function(e) {
    e.preventDefault();
    return false;
  });
  tab.addClass('disabled');
}

shinyjs.enableTab = function(name) {
  var tab = $('.nav li a[data-value=' + name + ']');
  tab.unbind('click.tab');
  tab.removeClass('disabled');
}
"

css <- "
.nav li a.disabled {
  background-color: #aaa !important;
  color: #333 !important;
  cursor: not-allowed !important;
  border-color: #aaa !important;
}"
# Create Shiny object

library(shiny)
library(shinythemes)
library(shinyjs)
library(ggplot2)
library(grid)
library(egg)

# source("input.r")
source("functions.r")
formula_tabs<-tabsetPanel(
  tabPanel("double_sig",
           withMathJax("$$y=d+\\frac{a}{1+exp^{-b*(t-c)}}+\\frac{e}{1+exp^{-f*(t-g)}}$$")
  ),
  tabPanel("gompertz",
           withMathJax("$$y=b*exp^{\\ln(\\frac{c}{b})*exp^{-a*t}}$$")
  ),
  tabPanel("verhulst",
           withMathJax("$$y=\\frac{b*c}{b+(b-c)*exp^{-a*t}}$$")

  ),
  id = "formulas",
  type = "tabs"

)

fluidPage(useShinyjs(),theme = shinytheme("lumen"),useShinyjs(),tags$style("#params { display:none; } #formulas { display:none; }"),
          extendShinyjs(text = jscode),inlineCSS(css),
          navbarPage("Protein turnover model",id="tabs",
                     tabsetPanel(tabPanel("Input data",
                                          checkboxInput("multiple","Single file",value = FALSE),
                                          uiOutput("mult_files"),
                                          uiOutput("sing_file"),
                                          actionButton("disp_distr","Show distributions"),
                                          plotOutput("distr_plot"),
                                          plotOutput("distr_stade")
                     ),
                     tabPanel("Weight fitting",
                              fileInput("weight_data","Choose weight data to be fitted",accept = c("text/csv")),
                              div(style="display:inline-block",selectInput("method_we","Select fitting formula",choices = c("Logistic"="verhulst","Gompertz"="gompertz","Empiric"="empirique","Log polynomial"="log_poly","Double sigmoid"="double_sig"))),
                              div(style="display:inline-block",formula_tabs), ## "Contois"="contois",,"Noyau"="seed",
                              conditionalPanel("input.method_we=='verhulst'",textInput("par1_sig","Enter value of a",value =0.1),
                                               textInput("par2_sig","Enter value of b",value = 100),
                                               textInput("par3_sig","Enter value of c",value = 1)),
                              conditionalPanel("input.method_we=='gompertz'",textInput("par1_sig","Enter value of a",value =0.065),
                                               textInput("par2_sig","Enter value of b",value = 114.39),
                                               textInput("par3_sig","Enter value of c",value = 0.52)),
                              conditionalPanel("input.method_we=='empirique'",textInput("par1_sig","Enter value of a",value =5.38),
                                               textInput("par2_sig","Enter value of b",value = 8),
                                               textInput("par3_sig","Enter value of c",value = 7)),
                              conditionalPanel("input.method_we=='double_sig'",textInput("par1_sig","Enter value of a",value = 48),
                                               textInput("par2_sig","Enter value of b",value = 0.144),
                                               textInput("par3_sig","Enter value of c",value = 35),
                                               textInput("par4_sig","Enter value of d",value = 0.4),
                                               textInput("par5_sig","Enter value of e",value = 48),
                                               textInput("par6_sig","Enter value of f",value = 0.042),
                                               textInput("par7_sig","Enter value of g",value = 90)),
                              actionButton("fit_op","Fit"),
                              plotOutput("fitplot")
                     ),
                     tabPanel("mRNA fitting and calculation",
                              textInput("ksmin","Value of ksmin",value =3*4*3*3.6*24),
                              selectInput("fit_mrna","Select fitting formula",choices=c("3rd degree polynomial"="3_deg","6th degree polynomial"="6_deg","3rd degree logarithmic polynomial"="3_deg_log")),
                              actionButton("run_loop","Run calculation"),
                              disabled(downloadButton("downFile","Save results"))
                     ),
                     tabPanel("Results",id="tabRes",
                              uiOutput("select_res"),
                              plotOutput("fit_prot_plot")
                     )
                     ))
)
library(shiny)
library(shinythemes)
library(shinyjs)
library(ggplot2)
library(grid)
library(egg)

# source("input.r")
source("functions.r")

function(input, output, session) {
  js$disableTab("tabRes")
  fit_op<-reactiveValues(data=NULL)
  run_calc<-reactiveValues(data=NULL)
  en_but<-reactiveValues(enable=FALSE)
  theme<<-theme(panel.background = element_blank(),panel.border=element_rect(fill=NA),panel.grid.major = element_blank(),panel.grid.minor = element_blank(),strip.background=element_blank(),axis.text.x=element_text(colour="black"),axis.text.y=element_text(colour="black"),axis.ticks=element_line(colour="black"),plot.margin=unit(c(1,1,1,1),"line"))

  output$mult_files<-renderUI({
    if (!input$multiple){
      tagList(fileInput("prot_file","Choose protein file"),
              fileInput("mrna_file","Choose transcript file"))
    }
  })

  output$sing_file<-renderUI({
    if (input$multiple){
      tagList(textInput("protein_tab","Name of protein tab",value = "Proteines"),
              textInput("rna_tab","Name of mRNA tab",value = "Transcrits"),
              fileInput("data_file","Choose xls/xlsx file",accept=c(".xls",".xlsx")))
    }
  })
  observeEvent(input$method_we, {
    # updateTabsetPanel(session, "params", selected = input$method_we)
    updateTabsetPanel(session,"formulas",selected = input$method_we)
  })
  observe({
    if(!is.null(input$data_file)){
      inFile<-input$data_file
      list_data<-loadData(inFile$datapath,input$rna_tab,input$protein_tab,poids=F)
      mrna_data<-list_data$mrna
      prot_data<-list_data$prot
      test_list<-list_data$parse
      test_list<<-sample(test_list,3)
      clean_mrna_data<<-mrna_data[,-which(is.na(as.numeric(as.character(colnames(mrna_data)))))]
      clean_prot_data<<-prot_data[,-which(is.na(as.numeric(as.character(colnames(prot_data)))))]
    }
  }) 
  observe({
    if((!is.null(input$prot_file)) & (!is.null(input$mrna_file))){
      protFile<-input$prot_file
      mrnaFile<-input$mrna_file
      prot_data<-loadData(protFile$datapath,"","",poids=F)
      mrna_data<-loadData(mrnaFile$datapath,"","",poids=F)
      clean_mrna_data<<-mrna_data[,-which(is.na(as.numeric(as.character(colnames(mrna_data)))))]
      clean_prot_data<<-prot_data[,-which(is.na(as.numeric(as.character(colnames(prot_data)))))]

      total_data<-merge(mrna_data,prot_data)
      lista<-vector("list",nrow(mrna_data))
      for (i in seq(1,nrow(total_data))){
        lista[[i]]<-list("Protein_ID"=total_data[i,"Protein"],"Transcrit_ID"=total_data[i,"Transcrit"],"Transcrit_val"=as.matrix(total_data[i,3:29]),"Protein_val"=as.matrix(total_data[i,30:ncol(total_data)]),"DPA"=t)

      }
      # test_list<<-lista
      test_list<<-sample(lista,3)
    }
  })    
  observeEvent(input$disp_distr,{
    print("Plotting...")
    output$distr_plot<-renderPlot({print(combineGraphs(clean_mrna_data,clean_prot_data,"",moyenne = T))})
    print("Finished")
  })

  # parList<-reactiveValues()
  # observe({
  #   for (i in reactiveValuesToList(input)){
  #   print(i)
  #   if (grepl("par[1-9]+_sig",i,perl = T)){
  #     newlist[[input[[i]]]]<-input[[i]]
  #   }
  # }
  # # })

  parList<-reactive({
    x<-reactiveValuesToList(input)
    x_ind<-grep("par[1-9]+",names(x),perl = T)
    newlist<-vector("list",length(x_ind))
    names(newlist)<-names(x[x_ind])
    for (el in names(newlist)){
      newlist[[el]]<-as.numeric(as.character(input[[el]]))
    }
    names(newlist)<-gsub("_sig","",names(newlist))
    newlist<-newlist[order(names(newlist))]
    newlist
  })
  observeEvent(input$fit_op,{
    browser()
    print(parList())
    inFile<-input$weight_data
    days_kiwi<-rep(c(0,13,26,39,55,76,118,179,222), each = 3)
    poids_data<-loadData(inFile$datapath,"","",poids=T)
    print("Fitting...")
    tryCatch({
      coefs_poids<<-fitPoids_v2(poids_data[,1],poids_data[,2],input$method_we,parList())
    },
    warning = function(warn){
      showNotification(paste0(warn), type = 'warning')
    },
    error = function(err){
      showNotification(paste0(err), type = 'err')
    })
    print(coefs_poids$coefs)
    val_mu<-mu(c(poids_data$DPA),input$method_we,coefs_poids$coefs,coefs_poids$formula,dpa_analyse = NULL)
    data_mu<-data.frame("DPA"=c(poids_data$DPA),"Mu"=val_mu)
    g_mu<<-ggplot(data_mu,aes(x=DPA,y=Mu))+geom_line()+theme+xlab("DPA")+ylab("Growth rate (days^-1)")
    fit_op$state<-TRUE
    print("Finished!!")
    output$fitplot<-renderPlot({
      req((fit_op$state)==TRUE,exists("coefs_poids"))
      ggarrange(coefs_poids$graph,g_mu,ncol=2)
    })
  })
  observeEvent(input$run_loop,{
    if (input$fit_mrna!=""){
      ksmin=as.numeric(as.character(input$ksmin))
      score=0
      cont<-0
      poids_coef<<-coefs_poids$coefs
      formula_poids<<-coefs_poids$formula
      mess<-showNotification(paste("Running..."),duration = NULL,type = "message")
      for (el in test_list){
        tryCatch({
          run_calc$run<-TRUE
          cont<-cont+1
          print(cont)
          norm_data<-normaMean(el$Protein_val,el$Transcrit_val,ksmin)
          fittedmrna<<-fit_testRNA(el$DPA,norm_data$mrna,"3_deg")
          par_k<-solgss_Borne(el$DPA,as.vector(norm_data$prot),as.numeric(norm_data$ks),score)
          par_k[["plot_fit_prot"]]<-plotFitProt(el$DPA,as.vector(norm_data$prot),par_k$prot_fit)
          X<-matrice_sens(el$DPA,par_k[["solK"]][,1])
          diff<-(par_k[["error"]][["errg"]][1]*norm(as.vector(norm_data$prot),"2"))^2
          par_k[["corr_matrix"]]<-matrice_corr(X,length(norm_data$prot),diff)
          if (!is.null(par_k)){
            test_list[[cont]]$SOL<-par_k
            # write.csv(test_list[[cont]][["SOL"]][["solK"]],paste("solK/",paste(test_list[[cont]][["Transcrit_ID"]],"_Sol_ks_kd.csv"),sep = ""))
          }
        },error=function(e){showNotification(paste0("Protein fitting not achieved for ",el$Transcrit_ID,sep=" "),type = "error",duration = NULL)})

      }
      valid_res<<-Filter(function(x) {length(x) > 5}, test_list)
      print(valid_res[[1]])
      mess<-showNotification(paste("Finished!!"),duration = NULL,type = "message")
      en_but$enable<-TRUE

    }
  })
  output$downFile<-downloadHandler(
    filename = function(){
      paste("results_KsKd-",Sys.Date(),".zip",sep="")
    },
    content = function(file){
      owd <- setwd(tempdir())
      on.exit(setwd(owd))
      files <- NULL;
      for (res in valid_res){
        fileName<-paste(res[["Transcrit_ID"]],"_Sol_ks_kd.csv",sep = "")
        write.csv(res[["SOL"]][["solK"]],fileName)
        files<-c(files,fileName)
      }
      zip(zipfile = file,files = files)
      if(file.exists(paste0(file, ".zip"))) {file.rename(paste0(file, ".zip"), file)}
    },contentType = "application/zip"

  )
  observe({
    if (en_but$enable){
      enable("downFile")
    }
  })
}