我是R-Shiny的新手,我的问题可能很简单。经过数小时的思考和搜索,我无法解决问题。这是问题所在:

1)我的应用要求用户上传他的数据集。

2)然后,在服务器文件中,我读取了数据集,并进行了一些分析,并将结果报告回用户界面。

3)我的用户界面有4个不同的输出。

4)我在每个输出的“渲染”功能中读取了数据集。 问题:这样,就在每个函数的作用域中本地定义了数据,这意味着我需要为每个输出再次读取它。

5)这是非常低效的,还有其他选择吗?使用响应式(Reactive)?

6)下面是一个示例代码,显示了我如何编写服务器。R:

shinyServer(function(input, output) {

   # Interactive UI's:
   # %Completion

   output$myPlot1 <- renderPlot({
     inFile <- input$file

      if (is.null(inFile)) return(NULL)
      data <- read.csv(inFile$datapath, header = TRUE)

      # I use the data and generate a plot here

   })

   output$myPlot2 <- renderPlot({
     inFile <- input$file

      if (is.null(inFile)) return(NULL)
      data <- read.csv(inFile$datapath, header = TRUE)

      # I use the data and generate a plot here

   })

 })

如何只获取一次输入数据并仅在输出函数中使用数据?

非常感谢,

最佳答案

您可以使用reactive函数从文件中调用数据。然后可以例如访问它
其他myData()函数中的reactive:

library(shiny)
write.csv(data.frame(a = 1:10, b = letters[1:10]), 'test.csv')
runApp(list(ui = fluidPage(
  titlePanel("Uploading Files"),
  sidebarLayout(
    sidebarPanel(
      fileInput('file1', 'Choose CSV File',
                accept=c('text/csv',
                         'text/comma-separated-values,text/plain',
                         '.csv'))
    ),
    mainPanel(
      tableOutput('contents')
    )
  )
)
, server = function(input, output, session){
  myData <- reactive({
    inFile <- input$file1
    if (is.null(inFile)) return(NULL)
    data <- read.csv(inFile$datapath, header = TRUE)
    data
  })
  output$contents <- renderTable({
    myData()
  })

}
)
)

关于r - 处理R Shiny中的输入数据集,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24599141/

10-12 17:47
查看更多