我是Shiny的新手,所以在ui和服务器之间如何通信时遇到了麻烦。我想用动态过滤器参数创建一个ggplot2
条形图,所以我可以在textInput
小部件中输入一个单词,这样条形图就会改变。
我正在使用300个文档中的50,000个单词,这就是为什么我需要textInput的原因,但是这里有一些示例数据:
library(tidyverse)
library(shiny)
example_df <- tibble::tribble(
~doc, ~word, ~n,
"A", "sustainable", 5L,
"A", "migrants", 2L,
"A", "building", 4L,
"B", "sustainable", 2L,
"B", "together", 1L,
"B", "building", 5L
)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
textInput(inputId = "word",
label = "Word:",
value = "sustainable"),
),
mainPanel(
plotOutput(outputId = "barchart")
)
)
)
使用此代码,我已经遇到了一个我不明白的错误:
Error in tag("form", list(...)) : argument is missing, with no default
server <- function(input, output) {
output$barchart <- renderPlot({
example_df %>%
filter(word == input) %>%
arrange(desc(n)) %>%
head(20) %>%
ggplot(aes(x = reorder(doc, n),
y = n)) +
geom_col() +
theme_minimal()
})
}
我知道这个闪亮的代码可能是疯狂的,但所有帮助都值得赞赏!
答案 0 :(得分:1)
您有两个小错误:
首先:
sidebarPanel(
textInput(inputId = "word",
label = "Word:",
value = "sustainable"),
)
您只是有一个多余的逗号,这是不必要的,这就是您收到错误的原因。
第二次:
example_df %>%
filter(word == input)
您没有指定要使用的输入。正确的语法是filter(word == input$word)
,其中'word'是textInput的ID。
完整的更正代码:
library(tidyverse)
library(shiny)
example_df <- tibble::tribble(
~doc, ~word, ~n,
"A", "sustainable", 5L,
"A", "migrants", 2L,
"A", "building", 4L,
"B", "sustainable", 2L,
"B", "together", 1L,
"B", "building", 5L
)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
textInput(inputId = "word",
label = "Word:",
value = "sustainable")
),
mainPanel(
plotOutput(outputId = "barchart")
)
)
)
server <- function(input, output) {
output$barchart <- renderPlot({
example_df %>%
filter(word == input$word) %>%
arrange(desc(n)) %>%
head(20) %>%
ggplot(aes(x = reorder(doc, n),
y = n)) +
geom_col() +
theme_minimal()
})
}
shinyApp(ui, server)