【问题标题】:Errors in if statements in R Shiny checkBoxGroupInputR Shiny checkBoxGroupInput中的if语句错误
【发布时间】:2017-04-14 20:58:05
【问题描述】:

我在我的 R Shiny 应用程序中使用 checkBoxGroupInput 的 if 语句出现错误。请忽略我要输出的所有图都是相同的事实 - 我稍后会更改它。

代码如下:

library(shiny)
library(leaflet)
library(DT)
library(ggplot2)
library(dplyr)

r_colors <- rgb(t(col2rgb(colors()) / 255))
names(r_colors) <- colors()

plotdata <- read.csv("C:/Users/Anatoly/Documents/Collatz/RenameLater/RenameLater/MapsAndSuch/RShinyCoral.csv")
colnames(plotdata) <- c("Year1", "RLIMona", "Year2", "RLICatalina", "Year3", "RLILaParguera1998", "Year4", "RLILAPARGUERA2004")
parguera <- read.csv("C:/Users/Anatoly/Documents/Collatz/RenameLater/RenameLater/MapsAndSuch/RShinyCoral.csv")
parguera <- select(parguera, 5:8)
colnames(parguera) <- c("Year", "1998 Expedition", "Year", "2004 Expedition")
monaisland <- read.csv("C:/Users/Anatoly/Documents/Collatz/RenameLater/RenameLater/MapsAndSuch/RShinyCoral.csv")
monaisland <- select(monaisland, 1:2)
colnames(monaisland) <- c("Year", "Mona Island RLI")
islacatalina <- read.csv("C:/Users/Anatoly/Documents/Collatz/RenameLater/RenameLater/MapsAndSuch/RShinyCoral.csv")
islacatalina <- select(islacatalina, 3:4)
colnames(islacatalina) <- c("Year", "Isla Catalina RLI")



ui <- fluidPage(
    titlePanel("NOAA Coral Luminescence Data (RLI, 5-year Running Average)"),
  leafletOutput("mymap"),
  p(),
  fluidRow(
  column(3, actionButton("laparguera", "La Parguera Data"),
  actionButton("mona", "Mona Island Data"),
  actionButton("isla", "Isla Catalina Data"))),
  fluidRow(
  column(3, offset = 5, actionButton("visualize", "Visualize Data"))),
  fluidRow(
  column(7, offset = 5, checkboxGroupInput("checkbox", "Add to plot", 
  c("La Parguera" = "La Parguera", "Mona Island" = "Mona Island", "Isla Catalina" = "Isla Catalina"))),
  fluidRow(
  DT::dataTableOutput('tbl'), 
  plotOutput("plot1")
)
)
)
server <- function(input, output, session) {

  output$mymap <- renderLeaflet({
    leaflet() %>%
      addTiles() %>%
      addMarkers(lat = 17.95, lng = - 67.05, popup = "La Parguera ") %>%
      addMarkers(lat = 18.00, lng = -67.50, popup = "Mona Island") %>%
      addMarkers(lat = 18.2, lng = -69.00, popup = "Isla Catalina")
  })
  observeEvent(input$laparguera, {
    output$tbl <- DT::renderDataTable(DT::datatable(parguera, options = list(pagelength = 25)))
  })
  observeEvent(input$mona, {
    output$tbl <- DT::renderDataTable(DT::datatable(monaisland, options = list(pagelength = 25)))
  })
  observeEvent(input$isla, {
    output$tbl <- DT::renderDataTable(DT::datatable(islacatalina, options = list(pagelength = 25)))
  })
  observeEvent(input$visualize, {
    output$plot1 <- renderPlot( 
  {
    if (input$checkbox == c("Mona Island"))
    {
    gplot <- ggplot(data = plotdata) +
    geom_polygon(mapping = aes(x = Year1, y = RLIMona), na.rm = TRUE) +
      ylab("Candelas (5-year Running Average)" )
    print(gplot)
    }
    else if(input$checkbox == c("La Parguera", "Mona Island"))
    {
      gplot2 <- ggplot(data = plotdata) +
        geom_polygon(mapping = aes(x = Year1, y = RLIMona), na.rm = TRUE) +
        ylab("Candelas (5-year Running Average)" )
      print(gplot2)
    }
    else if (input$checkbox == c("La Parguera", "Mona Island", "Isla Catalina")) 
    {
      gplot3 <- ggplot(data = plotdata) +
        geom_polygon(mapping = aes(x = Year1, y = RLIMona), na.rm = TRUE) +
        ylab("Candelas (5-year Running Average)" )
      print(gplot3)
    }
    else if(input$checkbox == c("Mona Island", "Isla Catalina")) 
    {
      gplot4 <- ggplot(data = plotdata) +
        geom_polygon(mapping = aes(x = Year1, y = RLIMona), na.rm = TRUE) +
        ylab("Candelas (5-year Running Average)" )
      print(gplot4)
    }
  else if(input$checkbox == c("La Parguera", "Isla Catalina")) 
  {
    gplot5 <- ggplot(data = plotdata) +
      geom_polygon(mapping = aes(x = Year1, y = RLIMona), na.rm = TRUE) +
      ylab("Candelas (5-year Running Average)" )
    print(gplot5)
  }
  else if(input$checkbox == c("Isla Catalina")) 
  {
    gplot6 <- ggplot(data = plotdata) +
      geom_polygon(mapping = aes(x = Year1, y = RLIMona), na.rm = TRUE) +
      ylab("Candelas (5-year Running Average)" )
    print(gplot6)
  }
  else if(input$checkbox == c("La Parguera")) 
  {
    gplot7 <- ggplot(data = plotdata) +
      geom_polygon(mapping = aes(x = Year1, y = RLIMona), na.rm = TRUE) +
      ylab("Candelas (5-year Running Average)" )
    print(gplot7)
  }
  else if(is.null(input$checkbox)) 
  {
   print("Check some damn boxes")
  }

      })

})
}

shinyApp(ui, server)

我认为问题是,我真的不知道我从复选框中得到什么类型的输入。我认为它是一个字符向量,但我不确定,并且文档不是很有帮助(至少对我来说)。

谢谢。

【问题讨论】:

    标签: r if-statement checkbox shiny


    【解决方案1】:

    请注意,我通常更喜欢发布一些工作代码,但这次我不能,因为我无权访问您的数据:抱歉。

    一些考虑:

    • checkboxGroupInput 中,您只需要一个纯字符向量,即您不需要命名列等。
      • 生成的input$checkbox 是另一个字符向量
      • checkboxGroupInput 旨在一次允许多个输入,因此输出可以是包含多个条目的向量。
      • (次要)而不是 if 的级联,我通常更喜欢使用 switch(已编辑:但它仅适用于 1 个元素比较),因为它使代码更具可读性(但它是个人口味)。

    在您的情况下,为了降低错误风险(通常是由于多次响应式调用代码),您可以在 output$plot1 中使用

    cols <- isolate(input$checkbox)
    

    另外,除了output$plot1 的现有代码之外,您还可以通过这种方式消除observeEvent

    # snippet - not tested
    #
    # observeEvent(input$visualize, {  # this is redundant
        output$plot1 <- renderPlot( 
          if(is.null(input$visualize)) return()  # this is all you need to make output$plot1 reactive to input$visualize
          cols <- isolate(input$checkbox)
          if (cols == c("Mona Island"))
            {
    

    嵌套响应式元素的激增在 Shiny 中从来都不是一件好事(除其他外,它会导致不必要的代码重复运行,消耗 CPU 周期)。

    如果有用,我最近在 SO 上发布了一个带有 checkboxGroupInput 的代码示例。见here

    如果您仍然遇到错误,我建议您发布链接以允许我或其他人获取您的数据并回发一个工作示例。

    工作示例和“新 cmets”

    library(shiny)
    library(leaflet)
    library(DT)
    library(ggplot2)
    library(dplyr)
    
    r_colors <- rgb(t(col2rgb(colors()) / 255))
    names(r_colors) <- colors()
    
    plotdata <- read.csv("RShinyCoral.csv")
    colnames(plotdata) <- c("Year1", "RLIMona", "Year2", "RLICatalina", "Year3", "RLILaParguera1998", "Year4", "RLILAPARGUERA2004")
    parguera <- read.csv("RShinyCoral.csv")
    parguera <- select(parguera, 5:8)
    colnames(parguera) <- c("Year", "1998 Expedition", "Year", "2004 Expedition")
    monaisland <- read.csv("RShinyCoral.csv")
    monaisland <- select(monaisland, 1:2)
    colnames(monaisland) <- c("Year", "Mona Island RLI")
    islacatalina <- read.csv("RShinyCoral.csv")
    islacatalina <- select(islacatalina, 3:4)
    colnames(islacatalina) <- c("Year", "Isla Catalina RLI")
    
    
    
    ui <- fluidPage(
      titlePanel("NOAA Coral Luminescence Data (RLI, 5-year Running Average)"),
      leafletOutput("mymap"),
      p(),
      fluidRow(
        column(3, actionButton("laparguera", "La Parguera Data"),
               actionButton("mona", "Mona Island Data"),
               actionButton("isla", "Isla Catalina Data")),
    
        column(9, 
          actionButton("visualize", "Add to Plot"),
    
          checkboxGroupInput("checkbox", label = NULL, 
                                                 c("La Parguera",  "Mona Island", "Isla Catalina"))
          )),
        fluidRow(column(6, DT::dataTableOutput('tbl')), 
         column(6,  plotOutput("plot1"))
         )
    )
    server <- function(input, output, session) {
    
      output$mymap <- renderLeaflet({
        leaflet() %>%
          addTiles() %>%
          addMarkers(lat = 17.95, lng = - 67.05, popup = "La Parguera ") %>%
          addMarkers(lat = 18.00, lng = -67.50, popup = "Mona Island") %>%
          addMarkers(lat = 18.2, lng = -69.00, popup = "Isla Catalina")
      })
      observeEvent(input$laparguera, {
        output$tbl <- DT::renderDataTable(DT::datatable(parguera, options = list(pagelength = 25)))
      })
      observeEvent(input$mona, {
        output$tbl <- DT::renderDataTable(DT::datatable(monaisland, options = list(pagelength = 25)))
      })
      observeEvent(input$isla, {
        output$tbl <- DT::renderDataTable(DT::datatable(islacatalina, options = list(pagelength = 25)))
      })
    
    
      output$plot1 <- renderPlot({
        if(length(input$visualize) == 0 ) return()
        isolate({
          if(length(input$checkbox) == 0) return()
          incheckbox <- input$checkbox
        }) # end isolate
        if(length(incheckbox) == 1) {
        switch(incheckbox,
          "Mona Island"= { gplot <- ggplot(data = plotdata) +
                              geom_polygon(mapping = aes(x = Year1, y = RLIMona), na.rm = TRUE) +
                              ylab("Candelas (5-year Running Average)" )
                           print(gplot) },
          "Isla Catalina"= { gplot6 <- ggplot(data = plotdata) +
                              geom_polygon(mapping = aes(x = Year1, y = RLIMona), na.rm = TRUE) +
                              ylab("Candelas (5-year Running Average)" )
                             print(gplot6) },
          "La Parguera"= { gplot7 <- ggplot(data = plotdata) +
                              geom_polygon(mapping = aes(x = Year1, y = RLIMona), na.rm = TRUE) +
                              ylab("Candelas (5-year Running Average)" )
                           print(gplot7) }
                           ) # end switch
        } else if(length(incheckbox) == 2) {
                 if(all(c("La Parguera", "Mona Island") %in% incheckbox)) {
                    gplot2 <- ggplot(data = plotdata) +
                      geom_polygon(mapping = aes(x = Year1, y = RLIMona), na.rm = TRUE) +
                      ylab("Candelas (5-year Running Average)" )
                    print(gplot2)
              }  else if( all(c("Mona Island", "Isla Catalina") %in% incheckbox))  {
                      gplot4 <- ggplot(data = plotdata) +
                        geom_polygon(mapping = aes(x = Year1, y = RLIMona), na.rm = TRUE) +
                        ylab("Candelas (5-year Running Average)" )
                      print(gplot4)
              } else if(all(c("La Parguera", "Isla Catalina") %in% incheckbox))    {
                      gplot5 <- ggplot(data = plotdata) +
                        geom_polygon(mapping = aes(x = Year1, y = RLIMona), na.rm = TRUE) +
                        ylab("Candelas (5-year Running Average)" )
                      print(gplot5)  
                    }
             }  else if ( all(c("La Parguera", "Mona Island", "Isla Catalina") %in% incheckbox)) {
                      gplot3 <- ggplot(data = plotdata) +
                        geom_polygon(mapping = aes(x = Year1, y = RLIMona), na.rm = TRUE) +
                        ylab("Candelas (5-year Running Average)" )
                      print(gplot3)
              } 
    
        })
    
    
    }
    
    shinyApp(ui, server)
    

    上面的代码对我有用:)

    除了 UI 更改(使 UI 更整洁并看看发生了什么),关键是 if cascade`。 考虑:

    • if 仅适用于一个元素。如果将长度 >1 的向量与另一个 >1 的向量进行比较,则仅考虑第一个向量的第一个匹配元素。
    • 我不认为我的代码特别优雅(我不排除以后获得一些更好的想法!),但它应该可以工作(如果没有,请告诉我)。
    • 假设您选择了 3 个元素。 all(c("La Parguera", "Mona Island") %in% incheckbox) 永远是真的。这就是为什么目前我按元素数量拆分比较(但可能还有其他选择,使用其他 set 运算符,如 setdiff)。

      请让我知道它是否适合您。

    【讨论】:

    • 非常感谢您的帮助。不幸的是,我仍然无法让代码工作。我想弄清楚如何向您发送我的数据。 @恩佐
    • 你能得到数据吗?如果没有,我不确定如何在此处共享 CSV 文件。
    • @madhatter5 我设法下载并上传了一些工作代码。请注意,您会在我之前的回复中找到它下面我以前的 cmets。告诉我进展如何。
    • 非常感谢恩佐!我会尽快通知你的。我真的很感激。
    猜你喜欢
    • 1970-01-01
    • 2018-04-19
    • 2022-01-12
    • 1970-01-01
    • 2015-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-14
    相关资源
    最近更新 更多