【发布时间】:2019-03-03 19:00:26
【问题描述】:
我正在尝试创建一个闪亮的应用程序,用户可以在其中上传 .csv 文件,然后在该数据帧上应用过滤器,然后使用 ggplot2 进行绘图。不幸的是,当我尝试从应该上传的 .csv 中的变量创建选择输入菜单时,我偶然发现了一个问题。
为了创建一个简单的示例,我们可以将 diamonds 数据集从 ggplot2 导出为 .csv 文件:
write.csv(diamonds, "diamonds.csv")
然后创建闪亮的应用程序:
library(shiny)
library(shinyWidgets)
library(ggplot2)
ui <- fluidPage(
titlePanel("test shiny"),
# Sidebar with a slider input for number of bins
sidebarLayout(sidebarPanel(
fileInput('file1', 'Choose file to upload',
accept = c(
'text/csv',
'text/comma-separated-values',
'text/tab-separated-values',
'text/plain',
'.csv',
'.tsv'
)
),
tags$hr(),
pickerInput(
inputId = "caratx",
label = "Choose carat",
choices = c("Select all", unique(user_data$carat)),
multiple = TRUE
),
selectInput(
inputId = "clarityx",
label = "Choose distance: ",
choices = unique(user_data$clarity)
)
),
mainPanel(plotOutput("endplot"))
))
# Define server logic
server <- function(input, output) {
output$endplot <- renderPlot({
inFile <- input$file1
if (is.null(inFile))
return(NULL)
user_data <- read.csv(inFile$datapath, header = T,
sep = ",", quote = input$quote)
validate(
need(input$entityx, 'Please select at least one carat'),
need(input$indicatorx, 'Please select at least one clarity')
)
if (input$caratx %in% "Select all") {
user_data <- user_data %>%
filter(carat %in% input$caratx)
} else {
user_data <- user_data %>%
filter(carat %in% input$caratx) %>%
filter(clarity %in% input$clarityx)
}
user_data %>%
ggplot(aes(x = `cut`)) +
geom_point(aes(y = price), color = "red") +
geom_point(aes(y = depth), color = "blue")
})
}
# Run the application
shinyApp(ui = ui, server = server)
这是输出:
Error in unique(user_data$carat) : object 'user_data' not found
有没有办法让这个工作?
非常感谢!
【问题讨论】:
-
您需要将
user_data设为反应式表达式 (shiny.rstudio.com/tutorial/written-tutorial/lesson6) 并使用renderUI(shiny.rstudio.com/articles/dynamic-ui.html) 渲染pickerInput -
@kwiscion 你愿意提供一个完整的答案吗?