R Shiny中的if语句checkBoxGroupInput中的错误 [英] Errors in if statements in R Shiny checkBoxGroupInput

查看:73
本文介绍了R Shiny中的if语句checkBoxGroupInput中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的R Shiny App中,带有checkBoxGroupInput的if语句出现错误。请忽略以下事实,即我要输出的所有图都是相同的-稍后再更改。

I am getting errors in my if statements with checkBoxGroupInput in my R Shiny App. Please ignore the fact that all the plots I want to output are the same - I will change this later.

这里是代码:

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)

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

I think the problem is, I don't really know what type of input I get from the checkbox. I assumed it was a character vector, but I'm not sure, and the documentation wasn't very helpful (at least for me).

谢谢。

推荐答案

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

Please note that I normally prefer to post some working code, but this time I couldn't because I do not have access to your data: my apologies.

一些考虑因素:


  • checkboxGroupInput 中,您只需要一个纯字符矢量,即,您无需命名列等。


    • 生成的 input $ checkbox 是另一个字符向量

    • checkboxGroupInput 旨在一次允许多个输入,因此输出可以是具有多个输入的向量。

    • (次要),而不是级联的 if 我通常更喜欢使用switch(编辑:但仅适用于1个元素比较),因为它使代码更具可读性(但这是个人喜好)。

    • In checkboxGroupInput you just need a plain character vector, i.e. you don't need to name columns etc.
      • The resulting input$checkbox is another character vector
      • checkboxGroupInput is designed to allow more than one input at a time, so the output can be a vector with more than one entry.
      • (minor) Rather than a cascade of if I normally prefer to use switch (edited: but it works only for 1 element comparisons), as it makes the code more readable (but it is personal taste).

      在您的情况下,以减少出错的风险(通常是由于反应性调用) g代码多次),在 output $ plot1 中,您可以使用

      In your case, to decrease the risk of errors (often due to a reactive calling the code more than once), in output$plot1 you could use

      cols <- isolate(input$checkbox)
      

      此外,而不是 output $ plot1 ,您可以通过以下方式消除 observeEvent

      Also, rather than the existing code for output$plot1, you could eliminate an observeEvent in this way:

      # 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"))
              {
      

      嵌套的反应性元素的泛滥从来都不是一件好事(除其他因素外,它会不必要地导致代码重复运行,从而消耗CPU周期)。

      The proliferation of nested reactive elements is never a good thing in shiny (among other things it causes unnecessarily the code to run repeatedly, burning CPU cycles).

      如果有用,我最近在SO上用 checkboxGroupInput 发布了一个代码示例。在此处

      If useful, I recently posted on SO a code example with checkboxGroupInput. See it here

      仍然会出现错误,建议您发布链接以允许我或其他人获取您的数据并发回工作示例。

      If you still get errors I would suggest to post the links to allow me or others to get your data and post back a working example.

      工作示例和新评论

      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)
      

      代码上面的代码对我有用:)

      The code above works for me :)

      除了UI更改外(使UI更加整洁并查看发生了什么),关键是如果级联`。
      请注意:

      Apart the UI changes (made to get a bit tidier UI and see what was happening), the key is the if cascade`. Take into account:


      • 如果仅适用于一个元素。如果将长度大于1的向量与另一个大于1的向量进行比较,则仅考虑第一个向量的第一个匹配元素。

      • 我不认为我的代码特别优雅(我不会排除以后,以获得更好的主意!),但它应该起作用(请让我知道是否无效)。

      • 假设您选择了3个元素。 all(c( La Parguera,莫纳岛)%in%复选框)始终为真。这就是为什么我现在按元素数量划分比较的原因(但是可能还有其他选择,使用其他 set 运算符,例如 setdiff )。

      • if only works for one element. If you compare a vector of length >1 with another vector >1, only the first matching element of the first vector is considered.
      • I do not consider my code particular elegant (I do not exclude later to get some better ideas!), but it should work (please let me know if it doesn't).
      • Suppose you have selected 3 elements. all(c("La Parguera", "Mona Island") %in% incheckbox) would always be true. This is why currently I split the comparisons by number of elements (but there are probably other alternatives using other set operators like setdiff).

      请告诉我它是否适合您。

      Please let me know if it works for you.

      这篇关于R Shiny中的if语句checkBoxGroupInput中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆