You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R Shiny中如何使用reactive函数创建数据框生成wordcloud2词云

Shiny词云应用报错解决方案

报错根因

Input must be a vector, not a function报错本质是未加载对应包时,你代码里用到的term_stats未被识别为有效分词函数,管道传递的参数类型不匹配抛出的错误,你的代码核心问题有3个:

  • 缺失必要依赖包,term_stats、stopwords_en、wordcloud2相关功能都需要额外加载对应包才能生效
  • 排序函数使用错误,dplyr::order_by是临时排序辅助函数,不能直接用于管道末尾修改数据框排序,应该用dplyr::arrange
  • 未做空值和长度校验:用户未输入文本、或文本分词后总词数少于你设置的最大展示词数时,直接截取1:input$num会出现索引越界错误

修正方案

如果未安装相关依赖先执行安装命令:
install.packages(c("wordcloud2", "tidytext", "stopwords"))

完整可运行代码:

library(shiny)
library(colourpicker)
library(tidyverse)
library(wordcloud2)
library(tidytext)
library(stopwords)

# 预加载英文停用词表
stopwords_en <- stopwords(language = "en", source = "snowball")

ui <- fluidPage(
  h1("Word Cloud"),
  sidebarLayout(
    sidebarPanel(
      textAreaInput("text", "Enter text", rows = 7),
      numericInput("num", "Maximum number of words", value = 25, min = 1),
      colourInput("col", "Background color", value = "white")
    ),
    mainPanel(
      wordcloud2Output("cloud")
    )
  )
)

server <- function(input, output) {
  df_data <- reactive({
    # 空输入直接返回空结构避免报错
    if(nchar(input$text) == 0) return(tibble(word = character(), count = integer()))
    
    tibble(text = input$text) %>%
      unnest_tokens(word, text) %>%
      filter(!word %in% stopwords_en) %>%
      count(word, sort = TRUE, name = "count")
  })
  
  output$cloud <- renderWordcloud2({
    df <- df_data()
    # 取用户设置值和实际词数的较小值,避免索引越界
    use_n <- min(input$num, nrow(df))
    if(use_n == 0) return()
    
    wordcloud2(data = df[1:use_n, ],
               backgroundColor = input$col)
  })
}

shinyApp(ui = ui, server = server)

内容的提问来源于stack exchange,提问作者fkn_ez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 04:36:03