Tuesday, September 27, 2016

Building your First R Package



As of late July 2013, there were 4,714 packages on CRAN and another 671 on Bioconductor, with more being added daily. In the past, building a package had the potential to be mystifying and complicated but that is no longer the case, especially when using the Hadley Wickham’s devtools package.

As I have worked with lots of projects, I have built up lots of functions that help me produce result like data tables, graphs that I find useful. But in many cases, it happens that I reuse the function many times that feel really awkward. I have been a fan of the idea of personal R package. 

In this blog we are going too discussed about how to build perfect R package so that you don't have to keep thinking to yourself.

Step 1: Package you will need to create a package are:

install.packages("devtools")
library("devtools")
devtools::install_github("klutometis/roxygen")
library(roxygen2)

Step 2: Create your package directory
# set Path
setwd("C:/Users/admin1/Documents")

# Create Package
create("ownpack")

If you look in your parent directory (i.e. the path that you will set before creating package), you will now have a folder called ownPackage, and in it you will have two folders and one file called DESCRIPTION. The structure should be similar to below image

Step 3: Add Functions in your Package

When you create packages, you need to add function into it. I have some line of code where I am create a function.

#' R_fun Function
#'
#' This function helps you to check whether condition is TRUE or FALSE
#' @keywords ownpack
#' @export
#' @examples
#' R_fun()

R_fun<- function(i)
{
  if(i>11)
  {
    print("Hi condition is TRUE")
  }
  else{
    print("Hi condition is FALSE")
  }
}


After that save this file R_fun-function.R into your R directory. And also create a new file R_fun-package.R in same folder and paste above code into it. The structure looks like

Similar you can add lots of function into your package. I just add only one function so that you can understand better.

Step 4: Process your Documentation 

Now you need to create documentation from your annotations earlier. Firstly set the path

setwd ("C:/Users/admin1/Documents/ownPackage")
document ( )

This automatically adds in the .Rd files to the man directory, and adds a NAMESPACE file to the main directory.

Step 4: Install
Now we are ready to install the package. But before install this package we need to come to our parent directory.

setwd ("C:/Users/admin1/Documents ")
install ("ownPackage")      

Now your package is successfully installed, Now you can also check that your function is successfully work or not
# Include library
library(ownPackage)

# Try this command
?R_fun

# Assign Value
 R_fun(3)
[1] "Hi condition is FALSE"

If you are getting this result it means your function is perfectly work. Basically package building is a great way to make code portable between projects and to share it with other people. A package purely built with R code only requires working function that can pass the CRAN check using check and proper help files that can easily built by including roxygen2 documentation above functions and calling document. Building the package is as simple as using build.
This way you can build your own package in R. 




Friday, September 23, 2016

Plot Interactive High Charts using R

Highcharts is another way to represent the data manually. Highcharts is a charting library which is written in pure JavaScript language. Basically it provides an easy way of adding interactive charts to your website or web application. Highcharts is a product that was created by the Norway-based company, Highsoft.

Currently it supports many types of charts like line, spline, area, areaspline, column, bar, pie, scatter, and so on. 

Advantage:
·       ·        Highcharts have a lots of chart types with same format, style, flavor
·        You can create or modify themes to customize the charts beautifully.
·        Lots of function like tooltips, titles, credits, legends, etc.
·        Provide various chart type with same style scatters, bubble, line, time series, bar graphs, and Heatmaps etc.
·        Piping Style
·        Configure your charts in different ways using themes. There are inbuilt     themes provide by highcharter package like economist, financial times, google,   538  among others.
·        Plugins: motion, drag points,  fontawesome, url-pattern, annotations.
Disadvantage:
  • ·        Faceting is not possible in High charts
  • ·        It uses standard evaluation plot(data$x, data$y) instead something like plot(data, ~x, ~y).

In this post we are going to plot interactive combo high charts in R using rcharts package. In this tutorial we are also using shiny package of R. This package is mostly used to create web application using R language.

As you know in shiny package we have two files (ui.R and server.R). Firstly we try to create a user interface file. 

ui.R

library(shiny)

## Create Data
Tokyo  <-  c(7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6)
NewYork  <-  c(-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5)
Berlin  <-  c(-0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0)
London  <-  c(3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8)

## Define UI for application that draws a Combo Graph
shinyUI(fluidPage(
 
  # Application title
  titlePanel("Monthly Average Temperature"),
 
    # Show a plot
    mainPanel(
       showOutput("Graph", "Highcharts")

)))



After created a ui.R script, now come to server.R file.

server.R

library(shiny)
library(highcharter)

# Define server logic required to draw a Combo graph
shinyServer(function(input, output) {

# High Chart code for Plotting the Combo Graph
output$Graph <- renderChart({
    h1 <- Highcharts()

   # Tokyo Line Graph
    h1$series(data = Tokyo, type='spline', name='Tokyo')

   # New York Line Graph
    h1$series(data = NewYork, type='spline', name='New York')

  # Berlin Line Graph
    h1$series(data = Berlin, type='spline', name='Berlin')

  # London column Graph
    h1$series(data = London, type='column', name='London')

   # Set Legend Layout
    h1$legend(layout='vertical',align='right',verticaAlign='top',borderWidth=0)

   # Add xAxis label in a graph
    h1$xAxis(categories=c('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))

    h1$set(dom='Graph')
    h1
  })
 
})

There are lots of things and options to do with high charts. You can refer this link Highcharts options to get more information about function in Highcharts.

When you save both file and click on RunApp button, you will get same output as you see in below image.


When you will go to any point then it will show to the information regarding to that point. You can also visit http://www.highcharts.com/demo/  website to take demo for interactive high charts. 


Highcharts gives superb web design with high adaptability, and the highcharter package permits R clients to take full advantage of them. In case you're keen on discovering more about the usefulness of the package, I very prescribe perusing the highcharter package homepage page which contains an different variety of Highcharts, Highstock and Highmaps plots alongside test code to recreate them. 


Wednesday, September 21, 2016

Integrate R with MongoDB

MongoDB is a free and open source database that uses a document-oriented data model. MongoDB was created by Dwight Merriman and Eliot Horowitz who had confronted development and scalability issues with traditional relational database approaches while building Web application at DoubleClick.
MongoDB was written in C++ language. Classified as NoSQL database, MongoDB supports dynamic schema design and avoids the traditional table-based relational database structure in favor of JSON-like documents.
While R is a wonderful tool for statistical analysis, visualization and reporting. It is also free and open source tool which is mostly used by statisticians, Analyst and Data scientist.
Now here I am going to show how to extract data from a MongoDB with R. And also you will learn how to analyze the data in R.
Before starting R session, we need to install MongoDB in the local machine and then load the data into the database.

MongoDB Installation

The first step is to check the operating system architecture of your system either it is 64 bit or 32 bit using the following command.


umic os get osarchitecture

Now you know your system architecture, to install the MongoDB on windows, first download the latest release of MongoDB from http://www.mongodb.org/downloads. Download 64 bit 
MongoDB for windows, as 32-bit versions of MongoDB will not work with 64 bit windows.


After Downloading the MongoDB setup, Double click on it  and click on Next Then agree to the license agreement > click Next> choose the setup type as complete > and finally click on Install:

Once you click on installation is complete you can check where your mongoDB is installed in your Local Disk (C):



Note: In this bin directory there are a bunch of mongo executables out of which mongo and mongod are the important ones, since mongo is the shell and mongod is responsible for starting the server. So we would have to run them on the command line.

So in order to run the server and the shell we need to change the path of the directory so that we can access it through the shell (command prompt).

Go to the control panel and then System, then click on Advanced system settings. Next click on the environment variables and thereafter choose the Path variable from the system variables.

Next go to the directory where MongoDB is currently present and copy the path till the bin directory where the mongoDB utilities are present and then append it in the Path variable and click on ok button.

After that before starting the mongoDB server we need to create a \data\lib directory where mongod will put the data. 


md \data
md \data\db

Now mongoDB is successfully installed and you can start the mongoDB server by using the following command:
C:\Users\Admin> mongod 

Once the mongoDB server has started you can start the mongo shell in another command prompt:

                                               mongo

Stored Data into MongoDB

# Create Database
use MyDatabase

# Create Collection inside Student Database
db.createCollection(Student)
# Insert Data into Student Collection
db.Student.insert([
{Name: 'Vihaan', RollNo: 101, Marks: 89, City: 'Gurgaon'}
{Name: 'Rohit',RollNo: 102, Marks: 74, City: 'Delhi'},
{Name: 'Sangeeta',RollNo: 103, Marks: 68, City: 'Noida'}
])

# View Table
db.Student.find ().pretty ()


Access MongoDB Data into R

# Install rmongoDB package
library(devtools)
install_github(repo = "mongosoup/rmongodb")

# Include library
library(rmongodb)
# create a connection to mongodb localhost
mongo_data = mongo.create(host = "127.0.0.1:27017")

# check whether mongodb is connected
mongo.is.connected(mongo_data)
## [1] TRUE

# View Database of MongoDB
mongo.get.databases(mongo_data)
## [1] "db1"        "MyDatabase" "mydb"       "RDatabase"  "test"

# shows all databases present in mongodb
mongo.get.database.collections(mongo_data,db = "MyDatabase")
## [1] "MyDatabase.Student"

# This would suffice as this would convert the entire list into a data frame in R.
data1 = mongo.find.all(mongo_data, ns = "MyDatabase.Student",data.frame=TRUE)
head(data1)
##                        _id     Name RollNo Marks    City
## 1 57cab63481d052e22ef3247c   Vihaan    101    89 Gurgaon
## 2 57cab63481d052e22ef3247d    Rohit    102    74   Delhi
## 3 57cab63481d052e22ef3247e Sangeeta    103    68   Noida

# To View all the function of rmongodb Package
mongofunction<-ls("package:rmongodb")
mongofunction<-data.frame(mongofunction)
head(mongofunction)
##            mongofunction
## 1 as.character.mongo.oid
## 2         mongo.add.user
## 3      mongo.aggregation
## 4     mongo.authenticate
## 5    mongo.binary.binary
## 6  mongo.binary.function


You can do lots of things using RMongoDB package. You will use lots of functions and perform Data manipulation and visualization on it. 

Building Shiny APP using R

Introduction
Shiny is a new package from RStudio that can be used to build interactive web application straight from R. It may be sound so much surprisingly for R users who have no experience in web development. Even you can build useful web application with only few lines of code. You don’t need to know any HTML/CSS/JavaScript. Shiny package provides fast bidirectional communication between the web browser and R using the websockets package. Even you can also use HTML, CSS and JavaScript in your Shiny code for more flexibility. In fact you can do quite a lot with shiny: like display R Objects, tables, Plots or anything else you do in R. To get more information about shiny, you can visit Shiny Tutorial website.

This tutorial is a hands-on activity for learning how to build shiny apps. And how to include yoy R code in shiny app. 

Installation

Install.packages(“shiny”)

To ensure you successfully installed Shiny, try running one of the demo apps.

library(shiny)
runExample(‘01_hello’) 

Structure of a Shiny App

Shiny app have two components
        1. A user-interface script
        2.  A server script

The user-interface (ui) script controls the layout and appearance of your app. It is a source file named ui.R. While server.R script contains the instructions that your computer needs to build your app

To start shiny app, go to File-> New File Name -> Shiny Web app. It will give you two options.


First options is Single File, in this options only single file is created where you write your shiny code. In second options you will get two file ui.R and server.R.

If you selecting multiple File options. You will see by default example is already programmed in both scripts. Now we will see how to use Rscript code in shiny app. 

Create Box Plot using Shiny App
ui.R

library(shiny)
head(iris)

# Define UI for application that draws a histogram
shinyUI(fluidPage(
 
  # Application title
  titlePanel("Iris"),
 
  # Sidebar with a slider input for the number of bins
  sidebarLayout(
    sidebarPanel(
     h1("Boxplot of Iris Species")
     ),
   
    # Show a plot of the generated distribution
    mainPanel(
      plotOutput("myplot")
    )
  )
))


server.R

 library(shiny)
library(ggplot2)
shinyServer(function(input, output) {

  output$myplot <- renderPlot({

    p <- ggplot(data =iris, aes(x=Species,y=Sepal.Length, colors=factor(Species)))
 graph <- p+geom_boxplot(fill=heat.colors(3))
 print(graph)
   

  })

})

After saving the file, RStudio should recognize the shiny app, you should see the usual Run button at the top change to Run App.


If you don’t see the Run button, it means you either have very old version of RStudio, don’t have shiny installed. Click on Run button, and now your app should run.

Output:
You should see that console has some text printed in the form of listening on http://127.0.0.1: 3504. You will also notice that you cannot run any commands in the console. This is because R is busy-your R sessions is currently powering Shiny app and listening for user interface.
To stop the application, click on stop button and also you can press Escape button.
This is a simple way to encode R code in shiny App. Similarly you can do lots of things which you do in R. you can also plot Data Frame and so on. If you want to learn more   about this package go to Shiny Tutorial website.










Creating Compelling Pie Charts in Looker: A Step-by-Step Guide with Examples

Creating Compelling Pie Charts in Looker: A Step-by-Step Guide with Examples   In the realm of data visualization, pie charts are a clas...