第一个tabPanel未在R Shiny中呈现输出

fiei3ece  于 2023-02-17  发布在  其他
关注(0)|答案(1)|浏览(114)

下面是一个在主面板上创建3个tabPanel的应用程序的reprex代码。但是每次我运行第一个tabPanel时,都不会呈现输出。但是如果我切换到第二个/第三个tabPanel,然后返回到第一个tabPanel,结果就会显示出来。我如何使第一个tabPanel显示输出,而不将制表符从2切换回1或从3切换回1?

EDITED:小括号的重新排列,以便显示相关系数答案。

library(bslib)
library(car)
library(moments)
library(nortest)
library(shiny)
library(shinythemes)
library(shinyjs)

options(scipen = 999) # options(scipen = 0)

ui <- fluidPage(theme = bs_theme(version = 4, bootswatch = "minty"),
           
  navbarPage(title = div(span("Reg & Cor", style = "color:#000000; font-weight:bold; font-size:18pt")),

                tabPanel(title = "Methods",
                  sidebarLayout(
                    sidebarPanel(
                      withMathJax(),
                      shinyjs::useShinyjs(),
                      id = "sideBar", 
                      selectInput(
                        inputId = "dropDownMenu",
                        label = strong("Choose Statistical Topic"),
                        choices = c("A", "B", "C", "Regression and Correlation"),
                        selected = "Regression and Correlation",
                      ),
                      
                      conditionalPanel(
                        condition = "input.dropDownMenu == 'Regression and Correlation'",
                        
                        id = "RegCorPanel",
                        
                        textAreaInput("x", label = strong("x (Independent Variable)"), value = "635, 644, 711, 708, 836, 820, 810, 870, 856, 923", placeholder = "Enter values separated by a comma with decimals as points", rows = 3),
                        textAreaInput("y", label = strong("y (Dependent Variable)"), value = "100, 93, 88, 84, 77, 75, 74, 63, 57, 55", placeholder = "Enter values separated by a comma with decimals as points", rows = 3),
                        
                        radioButtons(inputId = "regressioncorrelation", label = strong("Analyze Data Using"), selected = c("Simple Linear Regression"), choices = c("Simple Linear Regression", "Correlation Coefficient"), inline = TRUE),

                        conditionalPanel(
                          condition = "input.regressioncorrelation == 'Correlation Coefficient'",
                          
                          checkboxInput("pearson", "Pearson's Product-Moment Correlation (r)"),
                        ),
                        
                        actionButton(inputId = "goRegression", label = "Calculate",
                                     style="color: #fff; background-color: #337ab7; border-color: #2e6da4"),
                        actionButton("resetRegCor", label = "Reset Values",
                                     style="color: #fff; background-color: #337ab7; border-color: #2e6da4") #, onclick = "history.go(0)"
                      ),
                    ),
                    
                    mainPanel(
                      div(id = "RegCorMP",

                          conditionalPanel(
                            condition = "input.regressioncorrelation == 'Simple Linear Regression'",

                            tabsetPanel(id = 'tabSet',
                                tabPanel(id = "SLR", title = "Simple Linear Regression",
                                     plotOutput("scatterplot", width = "500px"),
                                     br(),
                                     
                                     verbatimTextOutput("linearRegression"),
                                     br(),
                                     
                                     verbatimTextOutput("confintLinReg"),
                                     br(),
                                     
                                     verbatimTextOutput("anovaLinReg"),
                                 ),
                                 
                                tabPanel(id = "normality", title = "Normality of Residuals",

                                     verbatimTextOutput("AndersonDarlingTest"),
                                     br(),
                                     
                                     verbatimTextOutput("KolmogorovSmirnovTest"),
                                     br(),
                                     
                                     verbatimTextOutput("ShapiroTest"),
                                ),
                                
                                tabPanel(id = "resid", title = "Residual Plots",
                                    
                                    plotOutput("qqplot", width = "500px"),

                                    plotOutput("moreplots", width = "500px"),
                                ),
                          ),
                        ),
                          conditionalPanel(
                            condition = "input.regressioncorrelation == 'Correlation Coefficient'",

                            conditionalPanel(
                              condition = "input.pearson == 1",
                              
                              verbatimTextOutput("PearsonEstimate"),

                              verbatimTextOutput("PearsonCorTest"),

                              verbatimTextOutput("PearsonConfInt"),
                            ),
                          ),
                      ) # RegCorMP
                    ) # mainPanel
                  ), # sidebarLayout
                ), # Methods Panel
        )
  )
  
server <- function(input, output) {

    # String List to Numeric List
    createNumLst <- function(text) {
      text <- gsub("","", text)
      split <- strsplit(text, ",", fixed = FALSE)[[1]]
      as.numeric(split)
    }

    observeEvent(input$goRegression, {
      
      datx <- createNumLst(input$x)
      daty <- createNumLst(input$y)
      
      if(anyNA(datx) | length(datx)<2 | anyNA(daty) | length(daty)<2){
        # output$linearRegression <- renderPrint({ 
        # "Invalid input or not enough observations"
        #   })
        print("Invalid input or not enough observations")
      }
      else{
          if(input$regressioncorrelation == "Simple Linear Regression")
          {
            model <- lm(daty ~ datx)

          output$scatterplot <- renderPlot({
            plot(datx, daty, main = "Scatter Plot", xlab = "Independent Variable, x", ylab = "Dependent Variable, y", pch = 19) +
              abline(lm(daty ~ datx), col = "blue")
          })
            
          output$linearRegression <- renderPrint({ 
            summary(model)
          })
          
          output$confintLinReg <- renderPrint({ 
            confint(model)
          })
            
          output$anovaLinReg <- renderPrint({ 
              anova(model)
          })

          output$AndersonDarlingTest <- renderPrint({ 
            ad.test(model$residuals)
          })
          
          output$KolmogorovSmirnovTest <- renderPrint({ 
            ks.test(model$residuals, "pnorm")
          })

          output$ShapiroTest <- renderPrint({ 
            shapiro.test(model$residuals) 
          })
          
          output$qqplot <- renderPlot({
            qqPlot(model$residuals, main = "Q-Q Plot", xlab = "Z Scores",  ylab = "Residuals", pch = 19) 
          })
          
          output$moreplots <- renderPlot({
            par(mfrow = c(2,2))
            plot(model, which=1:4, pch = 19)
          })
        }

        else if(input$regressioncorrelation == "Correlation Coefficient")
        {
          output$PearsonEstimate <- renderPrint({ 
            cor.test(datx, daty, method = "pearson")$estimate
          })
          
          output$PearsonCorTest <- renderPrint({ 
            cor.test(datx, daty, method = "pearson")
          })

          output$PearsonConfInt <- renderPrint({ 
            cor.test(datx, daty, method = "pearson")$conf.int
          })
        } # Correlation
      }
    }) # input$goRegression

    observeEvent(input$goRegression, {
      show(id = "RegCorMP")
      showTab(inputId = 'tabSet', target = 'Simple Linear Regression')
      showTab(inputId = 'tabSet', target = 'Normality of Residuals')
      showTab(inputId = 'tabSet', target = 'Residual Plots')
    })
    
    observeEvent(input$resetRegCor, {
      # hideTab(inputId = 'tabSet', target = 'Simple Linear Regression')
      # hideTab(inputId = 'tabSet', target = 'Normality of Residuals')
      # hideTab(inputId = 'tabSet', target = 'Residual Plots')
      hide(id = "RegCorMP")
      shinyjs::reset("RegCorPanel")
    })

    observe(
      hideTab(inputId = 'tabSet', target = 'Simple Linear Regression')
    )

    observe(
      hideTab(inputId = 'tabSet', target = 'Normality of Residuals')
    )

    observe(
      hideTab(inputId = 'tabSet', target = 'Residual Plots')
    )
}
  
shinyApp(ui = ui, server = server)
ppcbkaq5

ppcbkaq51#

该问题是由于最后3个观察事件引起的:
取消对它们的注解,那么它将工作:

library(car)
library(moments)
library(nortest)
library(shiny)
library(shinythemes)
library(shinyjs)
library(bslib)

options(scipen = 999) # options(scipen = 0)

ui <- fluidPage(theme = bs_theme(version = 4, bootswatch = "minty"),
                
                navbarPage(title = div(span("Reg & Cor", style = "color:#000000; font-weight:bold; font-size:18pt")),
                           
                           tabPanel(title = "Methods",
                                    sidebarLayout(
                                      sidebarPanel(
                                        withMathJax(),
                                        shinyjs::useShinyjs(),
                                        id = "sideBar", 
                                        selectInput(
                                          inputId = "dropDownMenu",
                                          label = strong("Choose Statistical Topic"),
                                          choices = c("A", "B", "C", "Regression and Correlation"),
                                          selected = "Regression and Correlation",
                                        ),
                                        
                                        conditionalPanel(
                                          condition = "input.dropDownMenu == 'Regression and Correlation'",
                                          
                                          id = "RegCorPanel",
                                          
                                          textAreaInput("x", label = strong("x (Independent Variable)"), value = "635, 644, 711, 708, 836, 820, 810, 870, 856, 923", placeholder = "Enter values separated by a comma with decimals as points", rows = 3),
                                          textAreaInput("y", label = strong("y (Dependent Variable)"), value = "100, 93, 88, 84, 77, 75, 74, 63, 57, 55", placeholder = "Enter values separated by a comma with decimals as points", rows = 3),
                                          
                                          radioButtons(inputId = "regressioncorrelation", label = strong("Analyze Data Using"), selected = c("Simple Linear Regression"), choices = c("Simple Linear Regression", "Correlation Coefficient"), inline = TRUE),
                                          
                                          conditionalPanel(
                                            condition = "input.regressioncorrelation == 'Correlation Coefficient'",
                                            
                                            checkboxInput("pearson", "Pearson's Product-Moment Correlation (r)"),
                                          ),
                                          
                                          actionButton(inputId = "goRegression", label = "Calculate",
                                                       style="color: #fff; background-color: #337ab7; border-color: #2e6da4"),
                                          actionButton("resetRegCor", label = "Reset Values",
                                                       style="color: #fff; background-color: #337ab7; border-color: #2e6da4") #, onclick = "history.go(0)"
                                        ),
                                      ),
                                      
                                      mainPanel(
                                        div(id = "RegCorMP",
                                            
                                            conditionalPanel(
                                              condition = "input.regressioncorrelation == 'Simple Linear Regression'",
                                              
                                              tabsetPanel(id = 'tabSet',
                                                          tabPanel(id = "SLR", title = "Simple Linear Regression",
                                                                   plotOutput("scatterplot", width = "500px"),
                                                                   br(),
                                                                   
                                                                   verbatimTextOutput("linearRegression"),
                                                                   br(),
                                                                   
                                                                   verbatimTextOutput("confintLinReg"),
                                                                   br(),
                                                                   
                                                                   verbatimTextOutput("anovaLinReg"),
                                                          ),
                                                          
                                                          tabPanel(id = "normality", title = "Normality of Residuals",
                                                                   
                                                                   verbatimTextOutput("AndersonDarlingTest"),
                                                                   br(),
                                                                   
                                                                   verbatimTextOutput("KolmogorovSmirnovTest"),
                                                                   br(),
                                                                   
                                                                   verbatimTextOutput("ShapiroTest"),
                                                          ),
                                                          
                                                          tabPanel(id = "resid", title = "Residual Plots",
                                                                   
                                                                   plotOutput("qqplot", width = "500px"),
                                                                   
                                                                   plotOutput("moreplots", width = "500px"),
                                                          ),
                                              ),
                                              
                                              conditionalPanel(
                                                condition = "input.regressioncorrelation == 'Correlation Coefficient'",
                                                
                                                conditionalPanel(
                                                  condition = "input.pearson == 1",
                                                  
                                                  verbatimTextOutput("PearsonEstimate"),
                                                  
                                                  verbatimTextOutput("PearsonCorTest"),
                                                  
                                                  verbatimTextOutput("PearsonConfInt"),
                                                ),
                                              ),
                                            )
                                        ) # RegCorMP
                                      ) # mainPanel
                                    ), # sidebarLayout
                           ), # Methods Panel
                )
)

server <- function(input, output) {
  
  # String List to Numeric List
  createNumLst <- function(text) {
    text <- gsub("","", text)
    split <- strsplit(text, ",", fixed = FALSE)[[1]]
    as.numeric(split)
  }
  
  observeEvent(input$goRegression, {
    
    datx <- createNumLst(input$x)
    daty <- createNumLst(input$y)
    
    if(anyNA(datx) | length(datx)<2 | anyNA(daty) | length(daty)<2){
      # output$linearRegression <- renderPrint({ 
      # "Invalid input or not enough observations"
      #   })
      print("Invalid input or not enough observations")
    }
    else{
      if(input$regressioncorrelation == "Simple Linear Regression")
      {
        model <- lm(daty ~ datx)
        
        output$scatterplot <- renderPlot({
          plot(datx, daty, main = "Scatter Plot", xlab = "Independent Variable, x", ylab = "Dependent Variable, y", pch = 19) +
            abline(lm(daty ~ datx), col = "blue")
        })
        
        output$linearRegression <- renderPrint({ 
          summary(model)
        })
        
        output$confintLinReg <- renderPrint({ 
          confint(model)
        })
        
        output$anovaLinReg <- renderPrint({ 
          anova(model)
        })
        
        output$AndersonDarlingTest <- renderPrint({ 
          ad.test(model$residuals)
        })
        
        output$KolmogorovSmirnovTest <- renderPrint({ 
          ks.test(model$residuals, "pnorm")
        })
        
        output$ShapiroTest <- renderPrint({ 
          shapiro.test(model$residuals) 
        })
        
        output$qqplot <- renderPlot({
          qqPlot(model$residuals, main = "Q-Q Plot", xlab = "Z Scores",  ylab = "Residuals", pch = 19) 
        })
        
        output$moreplots <- renderPlot({
          par(mfrow = c(2,2))
          plot(model, which=1:4, pch = 19)
        })
      }
      
      else if(input$regressioncorrelation == "Correlation Coefficient")
      {
        output$PearsonEstimate <- renderPrint({ 
          cor.test(datx, daty, method = "pearson")$estimate
        })
        
        output$PearsonCorTest <- renderPrint({ 
          cor.test(datx, daty, method = "pearson")
        })
        
        output$PearsonConfInt <- renderPrint({ 
          cor.test(datx, daty, method = "pearson")$conf.int
        })
      } # Correlation
    }
  }) # input$goRegression
  
  observeEvent(input$goRegression, {
    show(id = "RegCorMP")
    showTab(inputId = 'tabset', target = 'Simple Linear Regression')
    showTab(inputId = 'tabSet', target = 'Normality of Residuals')
    showTab(inputId = 'tabSet', target = 'Residual Plots')
  })
  
  observeEvent(input$resetRegCor, {
    # hideTab(inputId = 'tabSet', target = 'Simple Linear Regression')
    # hideTab(inputId = 'tabSet', target = 'Normality of Residuals')
    # hideTab(inputId = 'tabSet', target = 'Residual Plots')
    hide(id = "RegCorMP")
    shinyjs::reset("RegCorPanel")
  })
  
  # observe(
  #   hideTab(inputId = 'tabSet', target = 'Simple Linear Regression')
  # )
  
  # observe(
  #   hideTab(inputId = 'tabSet', target = 'Normality of Residuals')
  # )
  # 
  # observe(
  #   hideTab(inputId = 'tabSet', target = 'Residual Plots')
  # )
}

shinyApp(ui = ui, server = server)

相关问题