如何在R中过滤数据并绘制词云?

时间:2018-06-20 17:02:19

标签: r filter shiny word-cloud

你好,我想画一个词云。用户可以在不同的文档之间进行过滤。过滤后,仅应显示过滤后的数据。我怎样才能做到这一点?我的数据集如下:

Dataset

我有selectInput(),客户可以在其中选择文件编号。首先,我希望只能选择一个,但以后可能还要选择多个。这是我的ui.R代码段:

            box(
              title = "Document Control",
              status = "primary",
              solidHeader = TRUE,
              width = 4,
              selectInput("doc", label="Select Document", choices = Wcloud.Data$document, selected = 1)
            ),

            #
            box(
              title = "Frequency Control",
              status = "primary",
              solidHeader = TRUE,
              width = 4,
              height = 142,
              sliderInput("minFreq", label = "Minimum Frequency", min = 1, max = 50, value = 15)
            ),

            #
            box(
              title = "Number Control",
              status = "primary",
              solidHeader = TRUE,
              width = 4,
              height = 142,
              sliderInput("maxNum", label = "Maximum Number of Words", min = 1, max = 100, value = 30)
            ),

            box(
              title = "Graph", 
              status = "danger", 
              solidHeader = TRUE,
              width = 12,
              plotOutput("plotWcloud")
            ),

还有我的服务器R代码段:

output $ plotWcloud <-renderPlot({

Wcloud.Data.filtered <- Wcloud.Data %>%

  filter(input$doc == document)

Wcloud.Data.filtered %>%

#set.seed(1234)
wordcloud(words = term, freq = count, min.freq = input$minFreq, max.words = input$maxNum, random.order=FALSE, rot.per=0.35, colors=brewer.pal(8, "Dark2"))

})

1 个答案:

答案 0 :(得分:0)

您需要以闪亮的形式构建反应式函数,因此R知道input$doc更改时会更新您的文档选择。我将亲自在一个reactive({})中计算过滤后的数据集,然后在renderPlot({})函数中调用此反应式过滤后的数据集。

filtered <- reactive({
Wcloud.Data.filtered <- Wcloud.Data %>%
  filter(document == input$doc)
}) 

renderPlot({
wordcloud(words = filtered()$term, freq = filtered()$count, 
min.freq = input$minFreq, max.words = input$maxNum, random.order=FALSE, 
rot.per=0.35, colors=brewer.pal(8, "Dark2"))

})

请记住对每个用户输入窗口小部件使用此逻辑,并注意反应数据帧filtered旁边的括号。这就是调用反应性数据集的方式。希望这会有所帮助