Thursday, 25 April 2019

A simple Shiny App

Creating an app using R-shiny. 

Before going straight to creating the app, let's take a look at how to install and include packages in R. I'm using R-studio for writing my code. You can download R-studio from here.

Installing packages in R:-

You can install packages in two was:

  1. By writing install.packages("name_of_the_package") For eg: if you want to install wordcloud2 package then you'll have to write install.packages("wordcloud2") .
  2. Open R-studio, Go to Tools-> install packages.

We will be creating a very basic app using basic functions just to get the idea how things work with Rshiny.
Let's start by installing some packages. I am not i
install.packages("shiny")
install.packages("shinydashboard")
install.packages("shinyWidgets")
install.packages("shinythemes")
install.packages("htmlwidgets")
install.packages("wordcloud2")
install.packages("ggplot2")

Now that you have installed packages successfully, lets include them in the code for further use.
Remember just installing packages wont work. You have to use either library(package_name) or require(package_name).
library(shiny)
library(shinydashboard)
library(shinyWidgets)
library(shinythemes)
library(htmlwidgets)
library(wordcloud2)
library(ggplot2)
library(MASS)


Time to Code!

There are three functions you need to create a Shiny app:

ui <- shinyUI( )

server= function(input, output){ }

shinyApp(ui, server)

Lets first create the outline:
  • We want 4 tabs.
  • We want to include some radio buttons.
  • We want to add some images.
  • We want some plots.
  • We want wordcloud.
  • We may want to improve its look and feel too.

First of all lets give our app a name i.e SimpleApp. shinyUI ()  is basically for making our app look good. You can insert themes, change back ground color, add buttons, etc etc. 

ui <- shinyUI(navbarPage(title="SimpleApp"))








navbarPage() is used to create a navigation bar. It can contain number of tabs. We will insert 4 tabs in it.


ui <- shinyUI(navbarPage(title="SimpleApp",
                         tabPanel("Tab-1"),
                         tabPanel("Tab-2"),
                         tabPanel("Tab-3"),
                         tabPanel("Tab-4")))






Now lets focus on Tab-1 which is also the homepage of our app.

tabPanel("Tab-1", fluidRow(h1("Welcome to the home page of SimpleApp") 




tabPanel("Tab-1", 
fluidRow(h1("Welcome to the home page of SimpleApp"),
box(title="SimpleApp left box", width= 6, 
p("This part of the homepage contains data in text format. This text data is totally random.")
                                             


I have put some extra text in the p( ) . It looks untidy right now. Lets justify it by adding 
p("This part of the homepage contains data in text format. This text data is totally random.", style = "text-align : justify")



You must be wondering why it is occupying only half of the page. That's because we have used box( .....width=6,.............). You can change width of the text according to your need. I chose width=6 because I'll be adding some images in the second half.

box(title = "SimpleApp right box",
 img(src='pizza.jpg', align = "center", width="100%", height ="450px"),
img(src='burger.jpg', align = "center", width="100%", height ="350px"))
                                         
Create a folder "www" in the same directory where your R script is. Put all the images in it.

So the complete code of Tab-1 will look like this:

tabPanel("Tab-1", fluidRow(h1("Welcome to the home page of SimpleApp"),
 box( title="SimpleApp left box", width= 6,
 p("This part of the homepage contains data in text format. This text data is totally random. ", style = "text-align : justify") ),
 box(title = "SimpleApp right box",
 img(src='pizza.jpg', align = "center", width="100%", height ="450px"),
 img(src='burger.jpg', align = "center", width="100%", height ="350px")
                                         ))),


Similarly, we want to show some plots in Tab-2.
For this I've used three data-sets which are already preset in R-studio(we will see hem in server part of the app). You can check more datasets by importing library(MASS) and after that type data(). You will be able to see a list of datasets.

tabPanel("Tab-2",
                       br(),
                       sidebarLayout(sidebarPanel(
radioButtons("radio2", "Select the food category", 
list("Indian"="ind", "Chinese"="chi", "Japanese"= "jap"))),
mainPanel(verbatimTextOutput("text2")
))),


radio2 is user defined id for radiobuttons.
verbatimTextOutput( ) is predefined and is used to to display text on the page.
text2 is also a user defined id.

tabPanel("Tab-3", 
                       br(),
sidebarLayout(sidebarPanel(
radioButtons("radio3", "Select the category you want to see the plot for", list("Cars data"= "cd", 
        "Air Passengers data"="ap", 
        "Co2 uptake"="co"))),
mainPanel(plotOutput("plot3"))
                       )),


The br() tag is used to give a little vertical space after the tab heading. list("item_name"="item_id") is used to give a unique identification to the items. In future we will use only id's and not entire item name. In above code, "Cars data" is item name and "cd" is its id and "radio3" is the id of radioButtons( )

radio3 is user defined id for radiobuttons.

plotOutput( ) is pre-defined and is used to display graphs, histograms etc.
plot3  is user defined id of plotOutput()



tabPanel("Tab-4",
sidebarPanel(
sliderInput("slider4" ,"Use the slider to get the desired output", min =1, max = nrow(demoFreq), value=c(10,80))),
 mainPanel(column(12,wordcloud2Output("word4",height="700px", width="950px" )))
 )


In Tab-4, we have included a wordcloud (literally a cloud of words). Ans the data used here is demoFreq( already present in R-studio).

slider4 is user defined id of sliderInput
wourdcloud2Output( )  is pre-defined and is used to display a wordcloud.
word4  is user defined id of wordcloud


So we are done with the UI part of our app.

Let's move on to the server part. server( ) is like the brain of any shiny-app. All the calculations are done in server( ). It does calculations, returns them to shinyUI( ) which displays the output on the page. server( input, output) means it has two parameters , takes input and returns output. As we discussed earlier, we will be using unique id's  for further operations.


server= function(input, output){
  
  output$text2 <- renderPrint({
    if (input$radio2 == "ind"){
      print("You have selected First Choice i.e Indian food")
      
    }
    if (input$radio2 == "chi"){
      print("You have selected second Choice i.e Chinese food")
      
    }
    if (input$radio2 == "jap"){
      print("You have selected third Choice i.e Japanese food")
      
    }
    
  })

let's see what above code tells us.
output$text2 <- renderPrint({ }) means whatever calculations we are going to do inside renderprint( ) will be assigned as output of "text2". Now you might remember "text2" is the unique id that we provided in UI part to display text.

if(input$radio2 =="ind") 
We have three choiced in radiobuttons- "Indian","Chinese", "Japanese" with their respective id's- "ind", "chi","jap" respectively.
And we already know "radio2" is the id of radiobuttons in Tab-2
The above if condition is checking that whether we have selected first radio button or not. It will map the id of radiobutton with choices and display the output accordingly.




Similarly, in Tab-3 we can do the same thing.
 output$plot3 <- renderPlot({
    if (input$radio3 == 'cd'){
    plot(cars)
    }
    
    if (input$radio3 == "ap"){
      plot(AirPassengers)
      
    }
    if (input$radio3 == "co"){
      plot(CO2)
    }})










And for Tab-4,
output$word4 <- renderWordcloud2({
    wordcloud2(demoFreq[min(input$slider4): max(input$slider4),], size=.3)
    
  })



If you want you can remove the [min (....) : max(.....)]  from wordcloud2( ), then it will always show the full wordcloud  everytime you run the app and there will no point of adding slider.
demoFreq[min( input$slider4) : max(input$slider4)]  says that you want to show wordcloud of demoFreq containing rows from min(input$slider4) to max(input$slider4).
These value will change every-time user change the slider. by default it will show wordcloud of demoFreq from row number 10 to row number 80.
Use the slider and take a look at the wordcloud.

If you want the complete script, you can go here. You might have to install some additional packages. Run it. and message me if you're having any difficulty.



THANKS!!


 




Monday, 22 April 2019

Installing packages in Python

Before we start installing any packages, we need to install PYTHON and PIP on windows.
  • Download python from this link. You can choose from different versions.
  • Run the .exe file. 
  • Don't forget to check "Add Python to environment variables" checkbox.
  • After installing python. to verify if its installed correctly or not, open command prompt and type python. If it is installed properly, you'll see this window.
Successful installation of Python
  • Now its time to install to install PIP.
  • To install PIP, download get-pip from here . Right on it and save as get-pip.py. Or copy everything and paste it in a notepad file then save it as get-pip.py.
  •  Open cmd in the folder where you have downloaded the get-pip.py file and type:
    • python get-pip.py
    • Sometimes py get-pip.py works instead of the above command.
  • It will install the PIP on your windows.
  • After it's installed successfully, you can start installing other packages using pip command:
    • pip install numpy
    • pip install pandas
    • pip install matplotlib

Sunday, 9 December 2018

Mcleodganj Trek


It was the month of July and the year was 2017.  Me and four of my friends were sitting at the tea stall in my college chatting about nothing senseful. And the next thing I remember we were on a bus to Kangra which is not more than an hour from Mcleodganj(~40 km). 
Pizza at Kangra <3



We then boarded another bus to Mcleodganj and then a cab to our hotel.



Hotel was decent and cost us Rs 700 for a night, so it was quite cheap. Food was decent. 


The reception area
Our room. Plenty of space for five people.
We spent the first day there itself, exploring the market and surrounding. It's not very cold at this time of the year. However, its started to drizzle at night.

Market

Next morning we started off early. Bought some cheap rain coats and we were good to go. It was raining heavily when we left the hotel. But as we kept on going, rain almost stopped. Although, it was still drizzling and the weather was too humid. Every now and then we had to remove the rain coat, wipe the sweat and wear it again. It was quite frustrating!

Yes! the guy attempting a dab is me.
Drizzle
The weather was a little foggy
The road might not be good but the view was superb. There is greenery everywhere. Lots and lots of plants and trees and grass. As we move on, there were some small water falls in our way.

There's a small stall here where we had our first coffee.
Some more pics of mother nature as we kept on climbing. You can sit there and admire the beauty for hours. We can literally touch the clouds. It was like nature was welcoming us.

Photo credit to my friend
A groupie is a must ;)
More clouds


The real climbing starts after some miles. Initially its nothing but a plain road. But, as we go ahead, we realized there is no road anymore. The trek starts now!


Coats are off. Cold and humid though.
Yes! we crossed it!
And it started raining again...

Coats ON !


After around 5 hours of trekking, we saw the top. We were completely tired af. But as soon as we came to know it was the end and we dont have to climb anymore, we all were feeling completely satisfied and happy of course.

You can either rent tents up there or small wooden huts. It's not advised to rent tent when its raining.

Thats where we stayed for the night

Dharamsala at night
You wont find aything fancy to eat on the top. We ate maggie and daal-chawal which was ridicoulsly tasty at that time. The next morning we were lucky to feel some sunlight.
My favorite pic of the trip.
So thats it. Overall, it was an exciting trip. You should definitely visit there once. Keep traveling and be happy!














A simple Shiny App

Creating an app using R-shiny.  Before going straight to creating the app, let's take a look at how to i nstall and include packages...