R Shiny checkBoxGroupInput中if语句中的错误

时间:2017-04-14 20:58:06

标签: r if-statement checkbox shiny

我的R Shiny App中的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)

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

感谢。

1 个答案:

答案 0 :(得分: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"))
        {

嵌套的被动元素的激增在闪亮中永远不是一件好事(除此之外,它会不必要地导致代码重复运行,燃烧CPU周期)。

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

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

工作示例和“新评论”

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级联。 考虑到:

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

    如果它适合您,请告诉我。