2016-03-10 56 views
3

因此,我正在R闪光灯中构建一个应用程序,要求用户上传.csv文件。一旦被R闪亮读入,我不确定如何实际操作该对象以供使用。通用代码语法如下:阅读R中的文件Shiny

的UI文件:

#ui.R 
# Define UI for random distribution application 
shinyUI(fluidPage(

    # Application title 
    titlePanel("ORR Simulator"), 

    # Sidebar with controls to select the random distribution type 
    # and number of observations to generate. Note the use of the 
    # br() element to introduce extra vertical spacing 
    sidebarLayout(
    sidebarPanel(
      fileInput('file1', 'Select the XXX.csv file', 
       accept=c('text/csv','text/comma-separated-values,text/plain','.csv')), 
     tags$hr(), 
      fileInput('file2', 'Select the YYY.csv file', 
       accept=c('text/csv','text/comma-separated-values,text/plain','.csv')), 
     tags$hr(), 
    numericInput("S", "Number of simulations to run:", 100), 

     mainPanel(
plotOutput("plot") 
    ) 
) 
)) 

服务器文件:

#server.R 
library(shiny) 

shinyServer(function(input, output) { 

text1 <- renderText({input$file1}) 
text2 <- renderText({input$file2}) 

file1 = read.csv(text1) 
file2 = read.csv(text2) 

output$plot <- renderPlot({ 

plot(file1[,1],file2[,2]) 

}) 


}) 

所以我本来期望文本1和文本容纳包括文件路径字符串到文件的位置,但似乎并非如此。 Ultimatley我只想读取两个数据集,从那里可以根据这两个数据集进行分析和输出。

当然,使用renderText也可能是错误的想法,所以如何更好地做到这一点的任何建议非常感谢。

回答

4

这里有一个很好的例子http://shiny.rstudio.com/gallery/file-upload.html。但为了完整,我在下面列出了工作答案。关键是您应该使用file$datapath来引用文件,并检查输入是否为NULL(当用户尚未上传文件时)。

server.R

#server.R 
library(shiny) 

shinyServer(function(input, output) { 

    observe({ 
     file1 = input$file1 
     file2 = input$file2 
     if (is.null(file1) || is.null(file2)) { 
      return(NULL) 
     } 
     data1 = read.csv(file1$datapath) 
     data2 = read.csv(file2$datapath) 
     output$plot <- renderPlot({ 
      plot(data1[,1],data2[,2]) 
     }) 
    }) 

}) 

ui.R

library(shiny) 

#ui.R 
# Define UI for random distribution application 
shinyUI(fluidPage(

    # Application title 
    titlePanel("ORR Simulator"), 

    # Sidebar with controls to select the random distribution type 
    # and number of observations to generate. Note the use of the 
    # br() element to introduce extra vertical spacing 
    sidebarLayout(
     sidebarPanel(
      fileInput('file1', 'Select the XXX.csv file', 
         accept=c('text/csv','text/comma-separated-values,text/plain','.csv')), 
      tags$hr(), 
      fileInput('file2', 'Select the YYY.csv file', 
         accept=c('text/csv','text/comma-separated-values,text/plain','.csv')), 
      tags$hr(), 
      numericInput("S", "Number of simulations to run:", 100) 
     ), 
     mainPanel(
      plotOutput("plot") 
     ) 
    )) 
) 
+0

灿都这样的:文件1 =输入$文件1 文件2 =输入$文件2 如果(is.null(文件1)|| (file2)){ return(NULL) } data1 = read.csv(file1 $ datapath) data2 = read.csv(file2 $ datapath)是否超出renderPlot?如果它在里面,那只是局部的那个情节?我将在多个选项卡上构建多个图表,因此我只想加载一次数据。 – RustyStatistician

+0

如果你把所有内容都放在'观察'中,那么它就会起作用。您可以观察多个输出。查看更新的答案 –

+0

真棒,谢谢! – RustyStatistician