Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R shiny: read a table from file and use it

Tags:

r

shiny

I want to read a data.frame from file and then use it for making plots later on. The problem is that when I read the data, it is part of an output Object and can not be used further. I want to use the data from the csv file to make many different plots. Here is a small example where the csv file have two columns, what I want to do is in the end of the function server.

shiny::runApp(list(
 ui=pageWithSidebar(
    headerPanel('Simple matrixInput')
    ,
    sidebarPanel(
        fileInput('file1', 'Choose CSV File',
                  accept=c('text/csv', 'text/comma-separated- values,text/plain', '.csv'))
        ,
        tags$hr(),
        checkboxInput('header', 'Header', TRUE),
        radioButtons('sep', 'Separator',
                     c(Comma=',',
                       Semicolon=';',
                       Tab='\t'),
                     'Comma'),

        radioButtons('dec', 'Desimal seperator',
                     c('komma'=",",
                       'punktum'="."), 'komma')
    )
    ,
    mainPanel(

        tableOutput(outputId = 'table.output'),
        plotOutput("plot1")
    ))
,
server=function(input, output){
    output$table.output <- renderTable({

        inFile <- input$file1

        if (is.null(inFile))
            return(NULL)

        tbl <- read.csv(inFile$datapath, header=input$header, sep=input$sep,  dec = input$dec)

        return(tbl)
    })

    #I also want to do this:
    #  output$plot1 <- plot(tbl[,1], tbl[,2])
}
)) 
like image 356
Anja Avatar asked Jan 02 '17 14:01

Anja


1 Answers

Make use of the reactive function :

Make the following changes in the server part of your App

library(shiny)

shinyServer(function(input, output) {

mydata <- reactive({

inFile <- input$file1

if (is.null(inFile))
  return(NULL)

tbl <- read.csv(inFile$datapath, header=input$header, sep=input$sep,  dec = input$dec)

return(tbl)
})

 output$table.output <- renderTable({
 mydata()
 })

 output$plot1 <- renderPlot({
  x <- mydata()[,1]
  plot(x)
 })
})
like image 92
Sachin Vardhan Avatar answered Oct 21 '22 20:10

Sachin Vardhan