Dynamic ggvis object in Shiny

前提是你 提交于 2019-12-01 07:12:07

问题


I'm trying to add a dynamic ggvis plot to a Shiny app. First, user picks a dimension, and then adds items from that dimension.

For global.R and sample data, see https://gist.github.com/tts/a41c8581b9d77f131b31

server.R:

shinyServer(function(input, output, session) {


  # Render a selectize drop-down selection box 
  output$items <- renderUI({

    selectizeInput(
      inputId = 'items', 
      label = 'Select max 4. Click to delete',
      multiple = TRUE,
      choices = aalto_all[ ,names(aalto_all) %in% input$dim],
      options = list(maxItems = 4, placeholder = 'Start typing')
    )

  })


  selected <- reactive({

    if (is.null(input$items)) {
      return(aalto_all)
    }
    df <- aalto_all[aalto_all[[input$dim]] %in% input$items, ]
    df$keys <-seq(1, nrow(df))
    df

  })


  selected %>% 
    ggvis(~WoS, ~NrOfAuthors, fill = ~School, key := ~keys) %>%
    layer_points() %>%
    add_tooltip(show_title) %>%
    bind_shiny("gv")


  show_title <- function(x=NULL) {
    if(is.null(x)) return(NULL)
    key <- x["keys"][[1]]
    selected()$Title20[key]
  }  


})

ui.R:

shinyUI(fluidPage(

  titlePanel('Some (alt)metric data for articles published since 2010'),

  sidebarLayout(
    sidebarPanel(
      selectInput(
        inputId = "dim", 
        label = "Dimension", 
        choices = dimensions,
        selected = c("Title")),
      uiOutput("items")
      ),


    mainPanel(

      tabsetPanel(
        # I'll add more tabs
        tabPanel("Plot with ggvis", ggvisOutput("gv"))
      )
    )
  )
))

This is OK

  1. in the beginning, when there are no items selected, and all data is plotted. This is a hack because the ggvis object throws an error if there is no data served.
  2. when all selected items are deleted (which is the same as 1.) and another dimension is chosen

But when I try to switch to another dimension without deleting the items first, I get this:

Error in `$<-.data.frame`(`*tmp*`, "keys", value = c(1L, 0L)) : 
replacement has 2 rows, data has 0

I understand that ggvis is very new and constantly developing, but I suspect that there is merely something in Shiny reactive values that is out of sync. If anyone could point out what I'm doing wrong, thanks a lot!


回答1:


The error is caused because you have a data.frame with zero rows and have a resulting 1:0. You can change your selected function to:

 selected <- reactive({
    if (is.null(input$items)) {
      return(aalto_all)
    }
    df <- aalto_all[aalto_all[[input$dim]] %in% input$items, ]
    df$keys <-seq_along(df[,1])
    if(nrow(df) == 0){
      return(aalto_all)
    }
    df
  })


来源:https://stackoverflow.com/questions/24554734/dynamic-ggvis-object-in-shiny

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!