文件上传后,如何在闪亮的应用中绘制图形

时间:2019-03-28 15:13:54

标签: r shiny

我有一个非常简单的csv文件。

> head(data)
  X Y
1 1 1
2 2 2
3 3 4
4 4 8

我正在尝试创建一个光亮的应用程序仪表板,以在文件上传后绘制这些数据。

这是我到目前为止所拥有的。

library(shinydashboard)


ui <- dashboardPage(
  dashboardHeader(title = "Basic dashboard"),
  dashboardSidebar(
    fileInput("file1", "Choose CSV File",
              multiple = TRUE,
              accept = c("text/csv",
                         "text/comma-separated-values,text/plain",
                         ".csv")),
    sidebarMenu(
      menuItem("Dashboard", tabName = "dashboard", icon = icon("dashboard")),
      menuItem("Widgets", tabName = "widgets", icon = icon("th"))
    )
  ),
  dashboardBody(
    tabItems(
      # First tab content
      tabItem(tabName = "dashboard",
              fluidRow(
                box(plotOutput("plot1", height = 250))
              )
      ),

      # Second tab content
      tabItem(tabName = "widgets",
              h2("Widgets tab content")
      )
    )
  )
)

server <- function(input, output) {
  options(shiny.maxRequestSize=100*1024^2)

  inFile <- input$file1
  data <- read.csv(inFile$datapath, header = input$header, stringsAsFactors = FALSE)

  output$plot1 <- renderPlot({
    plot(data)
  })
}

shinyApp(ui, server)

但是我遇到了错误

Error in .getReactiveEnvironment()$currentContext() : 
  Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)

从我已阅读的内容来看,读取的文件需要是被动的,然后需要由绘图调用,但是我对被动的概念并不熟悉,将不胜感激。

1 个答案:

答案 0 :(得分:2)

你可以

data <- reactive({
  inFile <- input$file1
  if(!is.null(inFile)){
    read.csv(inFile$datapath, header = input$header, stringsAsFactors = FALSE)    
  }
})

output$plot1 <- renderPlot({
  req(data())
  plot(data()$X, data()$Y)
})