R is a programming language and free software environment for statistical computing and graphics that is supported by the R Foundation for Statistical Computing.
Size: 27.69 MB
Language: en
Added: May 22, 2018
Slides: 145 pages
Slide Content
PROGRAMMING by Bs Ram
Why Do We Need Analytics ?
Why Do We Need Analytics? Data Analytics helps organizations harness their data and use it to identify new opportunities. DATA ANALYTICS Cost Reduction Faster, Better Decision Organization Analysis Better Marketing & Product Analysis
What is Business analytics? Business Analytics examines large and different types of data to uncover hidden patterns, correlations and other insights.
What is Data Visualization? Visualization allows us visual access to huge amounts of data in easily digestible visuals. Well designed data graphics are usually the simplest and at the same time, the most powerful.
Why R? Apart from being used as statistical language, it can also be used a programming language for analytical purposes. Apart from being one of the most dominant analytics tools, R also is one of the most popular tools used for data visualization Programming and Statistical Language Data Analysis and Visualization
Why R? R is a simple and easy to learn, read & write R is an example of a FLOSS (Free / Libre and Open Source Software) which means one can freely distribute copies of this software, read it’s source code, modify it, etc. Simple and Easy to Learn Free and Open Source Easy 2 Learn
R Installation Base https://cran.r-project.org/bin/windows/base / Download R 3.5.0 for Windows (62 megabytes, 32/64 bit) Windows Ubuntu Press Ctrl+Alt+T to open Terminal Then execute sudo apt-get update After that, sudo apt-get install r-base
R Installation R Studio Windows Ubuntu sudo apt-get install gdebi -core wget https://download1.rstudio.org/rstudio-1.0.44-amd64.deb sudo gdebi rstudio-1.0.44-amd64.deb rm rstudio-1.0.44-amd64.deb https:// www.rstudio.com/products/rstudio/download /
Download Here
R Installation R Studio Windows Ubuntu sudo apt-get install gdebi -core wget https://download1.rstudio.org/rstudio-1.0.44-amd64.deb sudo gdebi rstudio-1.0.44-amd64.deb rm rstudio-1.0.44-amd64.deb https:// www.rstudio.com/products/rstudio/download /
Module
Variables Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. R Basics A = 2 S <- “AU TVS Centre for Quality Management” TURE -> Y Memory A = 2 S <- “AU TVS Centre for Quality Management” Y = TURE
Function Syntax: functionName <- function(inputs) { body of the function which returns something} You must run/submit the function before you can use it Note that variable naming within a function is protected, and not altered by whatever your script is doing
Function # tests if a number if positive pos = function(x) { if(x >= 0) out = 1 if(x < 0) out = 0 return(out) } Input Output
Function > pos = function(x) { + if(x >= 0) out = 1 + if(x < 0) out = 0 + return(out) + } > pos (5) [1] 1 > pos (-5) [1] 0 Run the function first
Data Manipulation
Importing Data Into R
Open your file
Reading data from txt|csv files: R base functions R base functions for importing data: read.table (), read.delim (), read.csv (), read.csv2 () Reading a local file Reading a file from internet
Reading data from txt|csv files: R base functions
Fast Reading of Data From txt|csv Files into R: readr package Functions for reading txt|csv files: read_delim (), read_tsv (), read_csv (), read_csv2() Reading a file Reading a local file Reading a file from internet In the case of parsing problems Specify column types Reading lines from a file: read_lines () Read whole file: read_file ()
Fast Reading of Data From txt|csv Files into R: readr package
Reading data From Excel Files ( xls|xlsx ) into R
Exporting Data From R
Exporting Data From R Export Data From R to txt|csv|Excel files Writing data from R to a txt|csv file: R base functions Fast Writing of Data From R to txt|csv Files: readr package Writing data from R to Excel files ( xls|xlsx ) Saving data into R data format: RDATA and RDS Create and format word and powerpoint documents using R and ReporteRs package : Create and format Word documents Create a Word document from a template file Add a table into a Word document Create and format PowerPoint documents Create an editable graph from R software to PowerPoint
Writing data from R to a txt|csv file: R base functions R R base functions for writing data: write.table (), write.csv (), write.csv2 () Writing data to a file
Fast writing of Data From R to txt|csv Files: readr package Installing and loading readr : install.packages (“ readr ”) readr functions for writing data: write_tsv (), write_csv () Writing data to a file
Fast writing of Data From R to txt|csv Files: readr package
Writing data from R to Excel files ( xls|xlsx ) Installing xlsx package: install.packages (“ xlsx ”) Using xlsx package: write.xlsx ()
Writing data from R to Excel files ( xls|xlsx )
Saving data into R data format: RDATA and RDS Save one object to a file: saveRDS (object, file), readRDS (file) Save multiple objects to a file: save (data1, data2, file), load (file) Save your entire workspace: save.image (), load ()
Saving data into R data format: RDATA and RDS Saving and restoring one single R object:
Saving data into R data format: RDATA and RDS 2. Saving and restoring one or more R objects :
Saving data into R data format: RDATA and RDS 3. Saving and restoring your entire workspace
Create and format Word documents with R and ReporteRs package ReporteRs package, by David Gohel , provides easy to use functions to write and format Word documents . It can be also used to generate Word document from a template file with logos, fonts, etc. ReporteRs is Java-based solution, so it works on Windows, Linux and Mac OS systems. Install and load the ReporteRs R package Create a simple Word document Add texts : title and paragraphs of texts Format the text of a Word document using R software Add plots and images Add a table Add lists : ordered and unordered lists Add a footnote to a Word document Add R scripts Add a table of contents into a Word document
Create a Word document from a template file with R and ReporteRs package Quick introduction to ReporteRs package Create a Word document using a template file data <- iris [ 1 : 5 , ] data
Add a simple table
Create a Word document from a template file with R and ReporteRs package Quick introduction to ReporteRs package Create a Word document using a template file data <- iris [ 1 : 5 , ] data
Packages
dplyr data.table ggplot2 reshape2 readr tidyr lubridate Packages ggplot2 is a graphical package. But, it generally helps in visualizing data ( distributions, correlations) and making manipulations accordingly.
dplyr Package by Hadley Wickham . filter – It filters the data based on a condition select – It is used to select columns of interest from a data set arrange – It is used to arrange data set values on ascending or descending order mutate – It is used to create new variables from existing variables summarise (with group_by ) – It is used to perform analysis by commonly used operations such as min, max, mean count etc This package has everything (almost) to accelerate your data manipulation efforts. It is known best for data exploration and transformation. It’s chaining syntax makes it highly adaptive to use.
dplyr Package by Hadley Wickham . I have used 2 pre-installed R data sets namely mtcars and iris.
dplyr Package by Hadley Wickham . #read data > head( mydata )
dplyr Package by Hadley Wickham . #creating a local dataframe . Local data frame are easier to read
dplyr Package by Hadley Wickham . #now data will be in tabular structure > mynewdata
dplyr Package by Hadley Wickham . > myirisdata
dplyr Package by Hadley Wickham . #use filter to filter data with required condition filter( mynewdata , cyl > 4 & gear > 4 ) filter
dplyr Package by Hadley Wickham . #use filter to filter data with required condition filter( mynewdata , cyl > 4)
dplyr Package by Hadley Wickham . > filter( myirisdata , Species %in% c(' setosa ', ' virginica '))
dplyr Package by Hadley Wickham . >select( mynewdata , cyl,mpg,hp ) #use select to pick columns by name select
dplyr Package by Hadley Wickham . > select( mynewdata , - cyl , -mpg ) #here you can use (-) to hide columns
dplyr Package by Hadley Wickham . #hide a range of columns > select( mynewdata , -c( cyl,mpg ))
dplyr Package by Hadley Wickham . #select series of columns > select( mynewdata , cyl:gear )
dplyr Package by Hadley Wickham . #chaining or pipelining - a way to perform multiple operations mynewdata %>% select( cyl , wt , gear) %>% filter( wt > 2)
dplyr Package by Hadley Wickham . #arrange can be used to reorder rows > mynewdata %>% select( cyl , wt , gear)%>% arrange( wt )
dplyr Package by Hadley Wickham . # you can rename the variables using rename command > mynewdata %>% rename(miles = mpg) Rename
data.table Package Leave your traditional ways of sub setting rows and columns and use this package. With minimum coding, you can do much more. Using data.table helps in reducing computing time as compared to data.frame . #load data > data (" airquality ") > mydata <- airquality > head(airquality,6) --- > data(iris ) > myiris <- iris
data.table Package #select columns with multiple values. This will give you columns with Setosa # and virginica species > myiris [Species %in% c(' setosa ', ' virginica ')] # select columns. Returns a vector > mydata [,Temp]
data.table Package > mydata [,.( Temp,Month )] #returns sum of selected column > mydata [,sum(Ozone, na.rm = TRUE)] [ 1]4887 #returns sum and standard deviation > mydata [,.(sum(Ozone, na.rm = TRUE), sd (Ozone, na.rm = TRUE))]
data.table Package #grouping by a variable > myiris [,.( sepalsum = sum( Sepal.Length )), by=Species]
ggplot2 Package ggplot offers a whole new world of colors and patterns. If you are a creative soul, you would love this package till depth . Chart patterns covers almost every type of data representation except maps. ggplot is enriched with customized features to make your visualization better and better. > library(ggplot2 ) > library( gridExtra ) > df <- ToothGrowth
reshape2 Package this package is useful in reshaping data R base functions consist of ‘Aggregation’ option using which data can be reduced and rearranged into smaller forms, but with reduction in amount of information. Aggregation includes tapply , by and aggregate base functions. The reshape package overcome these problems. melt This function converts data from wide format to long format. It’s a form of restructuring where multiple categorical columns are ‘melted’ into unique rows.
reshape2 Package cast : This function converts data from long format to wide format. It starts with melted data and reshapes into long format. It’s just the reverse of melt function. It has two functions namely, dcast and acast . dcast returns a data frame as output. acast returns a vector/matrix/array as the output. #cast > mcast <- dcast ( mt , DateofBirth + Subject ~ variable) > mcast
readr Package ‘ readr ’ helps in reading various forms of data into R. With 10x faster speed. Here, characters are never converted to factors(so no more stringAsFactors = FALSE). This package can replace the traditional read.csv() and read.table () base R functions . Delimited files withread_delim (), read_csv (), read_tsv (), andread_csv2(). Fixed width files with read_fwf (), and read_table (). Web log files with read_log () > install.packages (' readr ') > library( readr ) > read_csv ('test.csv', col_names = TRUE)
tidyr Package This package can make your data look ‘tidy’. It has 4 major functions to accomplish this task. Needless to say, if you find yourself stuck in data exploration phase, you can use them anytime (along with dplyr ). gather() – it ‘gathers’ multiple columns. Then, it converts them into key:value pairs. This function will transform wide from of data to long form. You can use it as in alternative to ‘melt’ in reshape package. spread() – It does reverse of gather. It takes a key:value pair and converts it into separate columns. separate() – It splits a column into multiple columns. unite() – It does reverse of separate. It unites multiple columns into single column
tidyr Package #load package > library( tidyr ) #create a dummy data set > names <- c('A','B','C','D','E','A','B') > weight <- c(55,49,76,71,65,44,34) > age <- c(21,20,25,29,33,32,38) > Class <- c('Maths','Science','Social','Physics','Biology','Economics','Accounts')
tidyr Package #create a data set > Humidity <- c(37.79, 42.34, 52.16, 44.57, 43.83, 44.59) > Rain <- c(0.971360441, 1.10969716, 1.064475853, 0.953183435, 0.98878849, 0.939676146) > Time <- c("27/01/2015 15:44","23/02/2015 23:24", "31/03/2015 19:15", "20/01/2015 20:52", "23/02/2015 07:46", "31/01/2015 01:55 ") #build a data frame > d_set <- data.frame (Humidity, Rain, Time) #using separate function we can separate date, month, year > separate_d <- d_set %>% separate(Time, c('Date', ' Month','Year ')) > separate_d
tidyr Package # using unite function - reverse of separate > unite_d <- separate_d %>% unite(Time, c(Date, Month, Year), sep = "/") > unite_d
tidyr Package #using spread function - reverse of gather > wide_t <- long_t %>% spread(Key, Value) > wide_t
Lubridate Package Lubridate package reduces the pain of working of data time variable in R. The inbuilt function of this package offers a nice way to make easy parsing in dates and times . > install.packages (' lubridate ') > library( lubridate ) #current date and time > now () [ 1] "2015-12-11 13:23:48 IST“ #assigning current date and time to variable n_time > n_time <- now()