r - 在 R Shiny 中处理输入数据集

标签 r shiny

我是 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)函数中调用文件中的数据。然后可以访问它,例如 其他响应式(Reactive)函数中的myData():

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()
  })

}
)
)

enter image description here

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

相关文章:

javascript - 在 Cloud Foundry 上运行 Shiny 应用程序的 R 构建包和 Assets 的 JavaScript 构建包

在 RMarkdown/Shiny 文档中引用 HTML 样式复选框

javascript - 将JS代码保存到RCloud Asset Book中并在Shiny中调用

r - 如何在 Shiny 中单击添加/保留任意数量的绘图层

r - 在 R-Markdown 中的网格上显示多个 dygraph

r - 我的 .Rmd 文件变得非常长。是否可以将它和 source() 分开,它是 main .Rmd 中较小的部分?

rCharts Polychart : Adding horizontal or vertical lines to a plot

r - 从 RStudio 调用的 knitr 不保留加载包的顺序

r - 更改选择选项但保留以前选择的值

r - tryCatch在for循环中