Dynamic ggvis object in Shiny

2020-03-26 09:16发布

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!

标签: r shiny ggvis
1条回答
老娘就宠你
2楼-- · 2020-03-26 09:38

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
  })
查看更多
登录 后发表回答