【问题标题】:upload file and make it global in R shiny上传文件并使其在 R 中全局化
【发布时间】:2015-01-23 18:55:04
【问题描述】:

我将文件上传到闪亮(csv 或 excel)并使用文件数据创建一个对象。我希望这个对象是全局的,因为我在不同的输出中使用数据。

我的原始(简化)server.R 代码是:

shinyServer(function(input, output) {

  output$contents <- renderTable({

    inFile <- input$file1 
    if (is.null(inFile))
  return(NULL)
data <- read.csv(inFile$datapath, header = input$header, sep = input$sep,       quote = input$quote, dec = ".")

 data

  })

  output$grafic <- renderPlot({

    inFile <- input$file1
    if (is.null(inFile))
      return(NULL)

     data <- read.csv(inFile$datapath, header = input$header, sep = input$sep, quote = input$quote, dec = ".")

    barplot(table(data$SEVERIDAD), main="Severitat dels riscos detectats")

      })
})

所以,我必须重复代码才能创建对象“数据”两次。

阅读其他帖子后,我尝试了此代码但不起作用:

    inFile <- input$file1 
    if (is.null(inFile))
      return(NULL)
    data <- read.csv(inFile$datapath, header = input$header, sep = input$sep,       quote = input$quote, dec = ".")


shinyServer(function(input, output) {

data <- reactive(data)
  output$contents <- renderTable({

data <- data()
data

  })

  output$grafic <- renderPlot({

     data <- data()

    barplot(table(data$SEVERIDAD), main="Severitat dels riscos detectats")

      })
})

我认为最后一个代码不起作用,因为加载应用程序时无法上传任何文件。

谢谢!

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    为数据创建一个反应式表达式,然后将其用于您的所有魔法……请注意,该代码尚未经过测试,仅供本地使用(让我知道它是否有效)……用于全局实施你可以使用&lt;&lt;- 作为赋值运算符

    shinyServer(function(input, output) {
    
      # Read the file into my_data, storing the data in this variable
      my_data <- reactive({
        inFile <- input$file1 
        if (is.null(inFile))
          return(NULL)
        data <- read.csv(inFile$datapath, header = input$header, sep = input$sep,quote = input$quote, dec = ".")
        data
      })
      # Create the table
      output$contents <- renderTable({
        my_data()
      })
      # Create a plot
      output$grafic <- renderPlot({    
        barplot(table(my_data()$SEVERIDAD), main="Severitat dels riscos detectats")
    
      })
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-11
      • 2012-03-13
      • 1970-01-01
      • 2021-08-13
      • 2011-02-16
      • 1970-01-01
      • 2020-08-14
      • 1970-01-01
      相关资源
      最近更新 更多