(R Shiny + igraph) 处理对 updateSelectInput 中当前顶点列表的反应

(R Shiny + igraph) handling reactivity to current list of vertices in updateSelectInput

我正在编写一个简单的应用程序,它显示 igraph 图并允许我 select 删除一个顶点。

顶点列表在使用 updateSelectInput 删除后没有正确更新,我无法指出我是如何处理反应性错误的。该应用程序擦除单个顶点并且不允许用户擦除另一个顶点。

library(shiny)
library(igraph)


##################################################
# Define UI 
###################################################
g <- make_ring(10)

ui <- fluidPage(

   # Application title
   titlePanel("Delete vertices in graph"),

   # select with list of vertices in graph 
   sidebarLayout(
      sidebarPanel(
         selectInput("vertexToDelete",
                     "Vertex to delete",
                     choices = V(g),
                     width = "100px"),

         actionButton("goButtonDelete", 
                      "Evaluate", 
                      width = '160px')
         ),



      # Show a plot of the graph
      mainPanel(
         plotOutput("graphPlot")
      )
   )
)
#################################################################################
# Define server logic 
#################################################################################


server <- function(input, output, session) {

  output$graphPlot <- renderPlot({

     if(input$goButtonDelete !=0)
      isolate({
         g <- delete_vertices(g, input$vertexToDelete)
         print(g)
         updateSelectInput(session, "vertexToDelete", choices = V(g))
       })

     plot(g) 
    })
  }

# Run the application 
shinyApp(ui = ui, server = server)

```

您的删除不会持久化,因为 g <- delete_vertices(g, input$vertexToDelete) 实际上不会修改全局 g 对象。相反,它会创建一个本地 g 然后打印和绘制。全局g保持不变,下次使用

您可以使用 g <<- delete_vertices(g, input$vertexToDelete) 修改全局对象,但更优雅的方法是使用 reactiveValues 在图形更新时触发绘图。

第二个问题是您使用了未命名的顶点,这就是为什么它似乎总是最后一个(10、9...)被删除的原因。您可以使用 set_vertex_attr(g, "name", ...) 命名顶点(然后 V(g)$name 访问它们的名称)

最后,您可以使用observeEvent在点击actionButton时执行删除:

g <- make_ring(10) %>% set_vertex_attr("name", value = LETTERS[1:10])

ui <- fluidPage( 
  titlePanel("Delete vertices in graph"),
  sidebarLayout(
    sidebarPanel(
      selectInput("vertexToDelete", "Vertex to delete", choices=V(g)$name),
      actionButton("goButtonDelete", "Evaluate")
    ),
    # Show a plot of the graph
    mainPanel(plotOutput("graphPlot"))
  )
)

server <- function(input, output, session) {
  my <- reactiveValues(g=g)

  observeEvent(input$goButtonDelete,{
    my$g <- delete_vertices(my$g, input$vertexToDelete)
    updateSelectInput(session, "vertexToDelete", choices=V(my$g)$name)
    })

  output$graphPlot <- renderPlot(plot(my$g))
}

shinyApp(ui = ui, server = server)