选择数据来源(ui)
在之前的几个练习中,您使用了 3 种不同的词云数据来源:Art of War 一书、文本输入框,以及文本文件。不过,同一时间只有一种来源在工作。本练习中,您将为用户提供一种方式来选择用于生成词云的数据来源。
本练习是课程的一部分
案例研究:使用 R 的 Shiny 构建 Web 应用
练习说明
您的任务是为应用添加单选按钮,让用户选择词源来自 Art of War 一书、文本区域,或上传的文件。具体要求:
- 添加一个标签为 "Word source" 的单选按钮输入,其中包含三个选项:
- 选项的值应分别为 "book"、"own" 和 "file"。显示给用户的名称应分别为 "Art of War"、"Use your own words" 和 "Upload a file"。
交互式实操练习
通过完成这段示例代码来试试这个练习。
ui <- fluidPage(
h1("Word Cloud"),
sidebarLayout(
sidebarPanel(
# Add radio buttons input
___(
inputId = "source",
label = ___,
choices = c(
# First choice is "book", with "Art of War" displaying
"Art of War" = "book",
# Second choice is "own", with "Use your own words" displaying
___ = "own",
# Third choice is "file", with "Upload a file" displaying
___ = ___
)
),
textAreaInput("text", "Enter text", rows = 7),
fileInput("file", "Select a file"),
numericInput("num", "Maximum number of words",
value = 100, min = 5),
colourInput("col", "Background color", value = "white")
),
mainPanel(
wordcloud2Output("cloud")
)
)
)
server <- function(input, output) {
input_file <- reactive({
if (is.null(input$file)) {
return("")
}
readLines(input$file$datapath)
})
output$cloud <- renderWordcloud2({
create_wordcloud(input_file(), num_words = input$num,
background = input$col)
})
}
shinyApp(ui = ui, server = server)