Friday, November 20, 2015

Plot histogram in RStudio using Shiny

CODE:

# '#' denotes a comment
# install.packages("UsingR") uncomment if package is not installed
library(UsingR)
# install.packages("shiny") uncomment if package is not installed
library(shiny)
# install.packages("Hmisc") uncomment if package is not installed
library(Hmisc)
# install.packages("corrplot") uncomment if package is not installed
library(corrplot)

# getwd() gives the current directory where R looks up for files
wd <- getwd()
setwd(wd)

# this is a responsive ui which has a file input selector and a plot
ui <- fluidPage(
  fluidRow(
    fileInput('infile', 'Choose file to upload',
              accept = c(
                'text/csv',
                'text/comma-separated-values',
                '.csv'
              )
    ),
    plotOutput("distPlot")
  )
)

# logic for showing histogram in plot
server <- function(input, output) {
  plotdata <- reactive({
    filestr <- input$infile
    read.csv(filestr$name)
  })
  output$distPlot <- renderPlot({
    hist(plotdata())
  })
}

# this command processes the above code and launches the window containing the output
shinyApp(ui=ui, server=server)

NOTE:

Make sure you put the .csv file to process in working directory of R otherwise it will throw error: "'x' must be numeric" (you can check it with getwd() command).

OUTPUT:
(click on image to zoom in)