Wordcloud 不会随着 Shiny 中的新输入而更新

Wordcloud doesn't update with new input in Shiny

作为 shiny 应用程序 (testapp) 的一部分,我有以下功能。它为默认选择生成词云,但不更新新选择。

ui.R

library(shiny)
shinyUI(fluidPage(
  # Application title
  headerPanel("Word Cloud"),

  # Sidebar with selection inputs
  sidebarPanel(width = 6,
               selectInput("firm", label="Choose a firm:", 
                           choices = c("a","b"),
                           selected = "a" )

  ),

  # Show Word Cloud
  mainPanel(
    d3CloudOutput("Plot1", width = "100%", height = 500)
  )
))

server.R

library(shiny)
library(rWordCloud) #require(devtools);install_github('adymimos/rWordCloud')
library(data.table)
source("helpers.R")
df1<-readRDS("data/df1.rds")

shinyServer(function(input, output) {
  dataInput <- reactive({

    isolate({
        readydata(input$firm)

  })
   })

    output$Plot1 <- renderd3Cloud({
      data <- dataInput()
     d3Cloud(text = data$indiv,size=data$Freq)

   })

})

helpers.R

readydata<-function(company){
   data.frame(setDT(df1)[firm==company,list(Freq=.N),by=indiv][order(Freq,decreasing=TRUE)])
  }

数据df1在testapp的data文件夹里面。数据结构如下:

df1<-structure(list(firm = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("a", 
"b"), class = "factor"), indiv = structure(c(5L, 6L, 7L, 1L, 
4L, 5L, 6L, 7L, 1L, 4L, 3L, 2L, 3L, 2L, 3L, 2L, 8L, 8L, 8L, 8L
), .Label = c("bello", "billow", "dillow", "fellow", "hello", 
"kello", "nello", "tillow"), class = "factor")), .Names = c("firm", 
"indiv"), row.names = c(NA, -20L), class = "data.frame")

P.S。需要使用 data.table 因为我聚合了大量的组。它需要设置回 wordcloud 的数据框。

我认为你的问题出在这里:

dataInput <- reactive({
    isolate({
        readydata(input$firm)
    })
})

isolate 函数将确保 dataInput 不会对 isolatem 中的任何内容产生反应性依赖,在您的情况下是 dataInput 中的所有内容。如果你简单地删除 isolate 然后它应该按预期更新,我相信(我没有测试它)。

dataInput() 是否也被用作未发布的应用程序的一部分?如果没有,您可以缩短内容:

output$Plot1 <- renderd3Cloud({
      data <- readydata(input$firm)
      d3Cloud(text = data$indiv,size=data$Freq)
})

我没有使用过 renderd3Cloud - 您可能需要使用 data<-reactive({readydata(input$firm)}),然后将其称为 data()

javascript 文件 d3Cloud.js 中存在错误。我已将其修复在 rWordCloud (https://github.com/NikNakk/rWordCloud) 的一个分支上,并向 adymimos 提交了一个拉取请求。实际错误在 htmlwidgets/d3Cloud.js

的第 59 行
 if ( instance.lastValue !== undefined) {
   svg.remove();
   console.log('Clearing svg');
   var svg = d3.select(el).append("svg")
   .attr("class", "rWordCloud");
   instance.svg = svg;  
}

应该

 if ( instance.lastValue !== undefined) {
   instance.svg.remove();
   console.log('Clearing svg');
   var svg = d3.select(el).append("svg")
   .attr("class", "rWordCloud");
   instance.svg = svg;  
}

否则,您需要删除 isolate,您可以将 server.R 代码简化为:

shinyServer(function(input, output) {
  output$Plot1 <- renderd3Cloud({
    data <- readydata(input$firm)
    d3Cloud(text = data$indiv,size=data$Freq)
  })
})