2014-07-06 43 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