2014-07-06 40 views
9

我是R-Shiny的新手,我的问题可能非常简单。经过数小时的思考和搜索,我无法解决问题。这是问题:处理R中的输入数据集Shiny

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

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

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

4)我在每个输出的“渲染”功能中读取数据集。问题:通过这样做,数据在每个函数的范围内被本地定义,这意味着我需要为每个输出重新读取它。

5)这是非常无效的,有没有其他选择?使用反应?

6)下面是显示我怎么写我server.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 

    }) 

}) 

我怎么能刚刚得到的输入数据一次,并只用在我的输出功能的数据?

非常感谢,

回答

7

可以拨打一个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() 
    }) 

} 
) 
) 

enter image description here

+1

@jdharrison你好,非常感谢你的答案。我实际上尝试过,但我得到的错误是“类型'闭包'的对象不是子集”。 – Sam

+0

请注意,我后来在渲染函数中引用了“myData”,并将通过$运算符使用某些数据列。我在任何时候使用像myData $ col1这样的列时都会收到错误。 – Sam

+1

适合我。该列将被作为'myData()$ col1'访问,但是通常首先在你的反应函数中首先执行一些类似于'mydata < - myData()'的操作。 – jdharrison