0% found this document useful (0 votes)
7 views40 pages

Introduction to R Programming Guide

Uploaded by

latenight
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views40 pages

Introduction to R Programming Guide

Uploaded by

latenight
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Introduction

to
R Programming

Predictive Society and Data


Analytics Lab
Spring 2023
Getting Started with R

• What is R?
• What can you do in R?
• Installing R & R Studio
Overview •

RStudio IDE
Help and Navigation
• Installing Packages

Programming in R

• Basic Operations
• Basic Object Types
• Data Structures
• Control structures
• User-defined Functions
• I/O
• Useful build-in Functions
• Plotting

Probability and Statistics in R

• Sampling
• Distributions
• Statistical Tests
FES - Predictive Society and Data Analytics Lab 2
Getting Started with R: What is R?
R Language
• A well-developed, simple and effective programming language based on S
• Supports imperative, object-oriented and functional programming paradigm
• A vast collection of libraries available for efficient data manipulation and analysis

R Environment
• Open-source and available for Ubuntu, MacOS and Windows
• Highly customizable, flexible and powerful with convenient integration with python, C++, etc.
• Effective data storage and handling facility for fast data manipulation and analysis
• Publish-quality graphics producible both on-screen and on hardcopy

FES - Predictive Society and Data Analytics Lab 3


Getting Started with R: What can you do in R?
• Simple arithmetic calculations • Data analysis
• Linear and nonlinear modelling, time series
>5+5 analysis, classification, clustering, etc
[1] 10 (caret, cluster, igraph, e1071, spacyr, Nnet)
• Advanced calculations • Statistical and Data manipulation packages
(stats, car, prob, stringr, dplyr, tidyr)
> 3*exp(2) + log(10)/sqrt(2)
• Data Visualization
[1] 23.79534
• Well-designed publication-quality plots using
ggplot2
• Object-oriented programming and
functional programming
• Most python libraries has interfaces or
packages for R

FES - Predictive Society and Data Analytics Lab | 4


Getting Started with R: Installing R & RStudio
R installation

• The latest version of R can be downloaded from the CRAN [Link]


• Choose the distribution of R suitable for your operating system

RStudio installation

• The latest version of RStudio can be downloaded from


[Link]

Using R with Anaconda or Jupyter

• Alternatively, you can also use R with Anaconda or Jupyter.


• More information found here
[Link]
FES - Predictive Society and Data Analytics Lab 5
Getting Started with R: R Studio IDE

Workspace

Source Scripts

Visualization/Help
Console

FES - Predictive Society and Data Analytics Lab 6


Getting Started with R: Help and Navigation
• The working directory
# set the working directory # Standard syntax
> setwd("~/folder") > help(FUN)
# get the current working directory # FUN = some function (e.g. 'sum')
> getwd() # Short-hand syntax
[1] "~/folder“ > ?FUN

• System functions > ??FUN


# example
# Check arguments of a function  ?sum
> args(FUN)
# Get help with functions
 help(FUN)

FES - Predictive Society and Data Analytics Lab 7


Getting Started with R: Installing Packages
• From CRAN • From Other Repos

# Installing packages from CRAN R # Installing packages from Bioconductor


repository
repository
> [Link](‘survival’)
> [Link]('BiocManager’)
> [Link](pkgs = ‘survival’)
> BiocManager::install(‘graph’)

# Load package
# Installing packages from GitHub
> library(survival)
> [Link](‘devtools’)
>
devtools::install_github(‘tidyverse/ggplot2
’)

8
Getting Started with R

• What is R?
• What can you do in R?
• Installing R & R Studio
Overview •

RStudio IDE
Help and Navigation
• Installing Packages

Programming in R

• Basic Operations
• Basic Object Types
• Data Structures
• Control structures
• User-defined Functions
• I/O
• Useful build-in Functions
• Plotting

Probability and Statistics in R

• Sampling
• Distributions
• Statistical Tests
FES - Predictive Society and Data Analytics Lab 9
Programming in R: Basic Operations
•Assigning values to variables • Mathematical operators

# Using assignment operator '<-' ('=' * and / # Multiplication and


in other languages) division
> x <- (1 + 1/10%%3)^100 + and - # Addition and subtraction
> y <- 2^100 () # Parentheses: specify operation
> x == y order
[1] TRUE
# ^ or ** power:
# = is generally used for assigning 2^10 = 1024 = 2**10
values at function calls # %/% Integer division:
> pnorm(q, mean = 0, sd = 1, [Link] 10%/%3 = 3
= TRUE) # %*% Conformable matrix multi:
x %*% y
FES - Predictive Society and Data Analytics Lab | 10
Programming in R: Basic Object Types
• The basic elements are called “objects”

• Check type of an object

FES - Predictive Society and Data Analytics Lab 11


Programming in R: String Example
# Defining a string # Splitting sentence into words # Regular Expression
message1 <- 'Hello Everyone' strsplit(message2, " ") message3<-c("New Hampshire", "New
print(message1) [[1]] Jersey","New Mexico", "New York")
[1] "Hello Everyone" [1] "Welcome" "to" "this" "Program"
message2 <- "Welcome to this Program" grep("Jersey", message3)
print(message2) # change string to uppercase [1] 2
[1] "Welcome to this Program" message_upper <- toupper(message1)
cat("Uppercase:", message_upper) grep("New",message3)
# double quote inside of double quotes [1] Uppercase: HELLO EVERYONE [1] 1 2 3 4
example1 <- "This is "R" programming"
Error: malformed raw string literal # change string to lowercase grepl("New",message3)
at line 1 message_lower <- tolower(message1) [1] TRUE TRUE TRUE TRUE
cat("\nLowercase:", message_lower)
# use of nchar() to find length of [1] Lowercase: hello everyone gsub('[ *]','_',message3)
message1 [1] "New_Hampshire"
nchar(message1) # Get part of the string "New_Jersey" "New_Mexico" "New_York"
[1] 14 substr(message2, 1, 7)
[1] "Welcome"
# use paste() to join two strings
paste(message1, ",", message2, sep = " ")
[1] "Hello Everyone , Welcome to this
FES - Predictive Society and Data Analytics Lab 12
Program”
Programming in R: Data Structures
• Data Structures • Environment is also a type of List
• Vectors (Same data type)
 Elements needs to have character
• Matrix (Same data type) names (named elements)
• Array (High-dimensional mix data)
• List (Mix data) • Indices start with 1 (not zero)
• Data Frame (Mix data)
• Several object functions available to
• Factor (Categorical Data)
apply a function to all data in a
structure (without looping)

 apply(), lapply(), sapply() etc.

FES - Predictive Society and Data Analytics Lab 13


Programming in R: Data Structures Examples
Vectors Matrices
a<-c(3, 4, 1, 7, 12) a<-seq(2, 16, 4) a<-matrix(c(1,2,3,4,5,6), nrow = 3, ncol = 2, byrow =
a a TRUE)
[1] 2 6 10 14 a
[1] 3 4 1 7 12 [,1] [,2]
names(a)<-LETTERS [1:4] [1,] 1 2
a[3] a [2,] 3 4
[1] 1 A B C D [3,] 5 6 rbind(c(2,5,3),c(4,3,4
2 6 10 14 ))
a[1,2] [,1] [,2] [,3]
a[c(2,5)] a[“C”] [1] 2 [1,] 2 5 3
[1] 4 12 C [2,] 4 3 4
10 a[1,]
a[2:4] [1] 1 2 a <- c(2,5,6,2)
[1] 4 1 7 dim(a) <- c(2,2)
a[c(1,3),] a
[,1] [,2] [,1] [,2]
a<-c(a,8) [1,] 1 2 [1,] 2 6
[1] 3 4 1 7 12 8 [2,] 5 6 [2,] 5 2

a<-append(a,10, after=length(a)) rownames(a) <- letters[1:3]


colnames(a) <- c("white", "black")
a
[1] 3 4 1 7 12 8 10 a[,”white”]
FES - Predictive Society and Data Analytics Lab 14
[1] 1 3 5
Programming in R: Data Structures Examples
Lists Arrays
a<-matrix(c(1,2,3,4), nrow = 2, ncol = 2, byrow = TRUE) a<-array(1:8, dim = (2,2,2))
b<<- list(a, “hello”, 3, c(4,2)) a[,,1]
b , , 1
[[1]] [,1] [,2]
[,1] [,2] [1,] 1 3
[1,] 1 2 [2,] 2 4
[2,] 3 4
a[2,2,1]
[[2]] [1] 4
[1] "hello"

[[3]]
[1] 3
Factor (Kind of a sorter)
[[4]] height <-factor(c(“small”, “medium”, “tall”,
[1] 4 2
“small”, “medium”))
names(b) <- LETTERS[1:4] height
b$C [1] small medium tall small medium
[1] 3 Levels: medium small tall

FES - Predictive Society and Data Analytics Lab 15


Programming in R: Data Structures Examples
# Create the data frame. # Get the structure of the data frame.
[Link] <- [Link]( str([Link])
emp_id = c (1:5), '[Link]': 5 obs. of 4 variables:
$ emp_id : int 1 2 3 4 5
emp_name = c("Rick","Dan","Michelle","Ryan","Gary" $ emp_name : chr "Rick" "Dan" "Michelle" "Ryan" ...
), $ salary : num 623 515 611 729 843
salary =c(623.3,515.2,611.0,729.0,843.25), $ start_date: Date, format: "2012-01-01" "2013-09-23" ...
start_date = [Link](c("2012-01-01", "2013-09-
23", "2014-11-15", "2014-05-11", "2015-03-27")), # Print the summary.
stringsAsFactors = FALSE summary([Link])
) emp_id emp_name salary
# Print the data frame. start_date
print([Link]) Min. :1 Length:5 Min. :515.2 Min. :2012-
01-01
emp_id emp_name salary start_date 1st Qu.:2 Class :character 1st Qu.:611.0 1st Qu.:2013-
1 1 Rick 623.30 2012-01-01 09-23
2 2 Dan 515.20 2013-09-23 Median :3 Mode :character Median :623.3 Median :2014-
3 3 Michelle 611.00 2014-11-15 05-11
4 4 Ryan 729.00 2014-05-11 Mean :3 Mean :664.4 Mean :2014-
5 5 Gary 843.25 2015-03-27 01-14
3rd Qu.:4 3rd Qu.:729.0 3rd Qu.:2014-
FES - Predictive Society and Data Analytics Lab 16
11-15
Programming in R: Data Structures Examples
# Extract Specific columns. # Add the "dept" coulmn.
result <-
[Link]$dept <-
[Link]([Link]$emp_name,[Link]$salar
y) c("IT","Operations","IT","HR","Finance")
print(result) v <- [Link]
[Link].emp_name [Link] head(v,2)
1 Rick 623.30 emp_id emp_name salary start_date
2 Dan 515.20 dept
3 Michelle 611.00 1 1 Rick 623.30 2012-01-01
4 Ryan 729.00 IT
5 Gary 843.25 2 2 Dan 515.20 2013-09-23
Operations
# Extract first two rows.
result <- [Link][1:2,] print(v)
print(result) emp_id emp_name salary start_date
emp_id emp_name salary start_date dept
1 1 Rick 623.3 2012-01-01 1 1 Rick 623.30 2012-01-01
2 - Predictive2Society and Data
Dan 515.2 2013-09-23 IT
FES Analytics Lab 17
2 2 Dan 515.20 2013-09-23
Programming in R: Data Structures Examples
# Merge two dataframes # Bind the two data frames by row
# Create a second data frame [Link] <- rbind([Link],[Link])
print([Link])
[Link] <- [Link](
emp_id = c (6:8), emp_id emp_name salary start_date dept
emp_name = 1 1 Rick 623.30 2012-01-01
c("Rasmi","Pranab","Tusar"), IT
salary = c(578.0,722.5,632.8), 2 2 Dan 515.20 2013-09-23
start_date = [Link](c("2013-05-21", Operations
"2013-07-30","2014-06-17")), 3 3 Michelle 611.00 2014-11-15
dept = IT
c("IT","Operations","Fianance"), 4 4 Ryan 729.00 2014-05-11
stringsAsFactors = FALSE HR
) 5 5 Gary 843.25 2015-03-27
Finance
6 6 Rasmi 578.00 2013-05-21
IT
FES - Predictive Society and Data Analytics Lab 18
7 7 Pranab 722.50 2013-07-30
Programming in R: Control Structures
• If-conditions • For loop
 First  3.  First

 d

 Second

 Second

 third
FES - Predictive Society and Data Analytics Lab 19
Programming in R: Control Structures
While loop • Other Functions usable for control
1. Ifelse() for vectors

2. Switch() to replace nested ifs


Repeat Loop

FES - Predictive Society and Data Analytics Lab 20


Programming in R: User-defined Functions
• Two-ways to define a function • Scope rules applies to R Functions
• The following will cause error

• Returning values

• Call with arguments or named arguments

• Can have many inputs but one


output (return data structure if many outs)
FES - Predictive Society and Data Analytics Lab 21
Programming in R: I/O
Reading
To load specified data sets, or list available in an R session use data().
from > library(survival) # Load datasets in survival
package
Packages > data(cancer)

Reading
To load files saved using R save() (i.e., ‘.rda’ or ‘.Rdata’) use load()
Data saved # Load .rda or .Rdata files
> load(“[Link]”)
by R
[Link]() # read a comma seperated file [Link]() # read a file in table format
[Link]() # read a TAB delimited file [Link]() # read a fixed width
From other format table
file types [Link]() # read data interchange format file
file
readLines() # Read individual lines from a

scan() # foundation for most other read functions

FES - Predictive Society and Data Analytics Lab 22


Programming in R: I/O
save(a,file="filename")

save(a, b,c,d,file="filename")
Saving
e<-c("a","b","c","d") save(list=e,file="filename")
Data in R
save(list=ls(all),file="filename")

[Link](file="filename")

Save to [Link]() #read a comma seperated file


other types write.csv2() #read a file with TAB
[Link]() #read a file in table format
of files

FES - Predictive Society and Data Analytics Lab 23


Programming in R: Useful Built-in Functions
• Mathematical Functions
• atan(), sin(), cos(), tan(), exp(), log(), log10(), sqrt(), floor(),
ceiling(), round(), abs(), factorial(), trunc()

• Vector Functions
• ave(), sort(), dim(), sum(), prod(), sample(), mean(), median(),
union(), unique(), sd(), quantilie(), range(), diff(), min(), max()

• String Functions
• substr(), grep(), sub(), paste(), strsplit(), tolower(), toupper()

FES - Predictive Society and Data Analytics Lab | 24


Programming in R: Plotting
• Plots are used for data visualization in R, use “? • Plotting with ggplot2 Object
plot” to see the full description
• Powerful plotting package with a wide variety
# Examples of options
plot(readData$Height, type="l",
col=”black")
[Link]("ggplot2")
boxplot(myDF, col = rainbow(3))
library(ggplot2)
hist(readData$Weight)
• Saving plots in different file format ?ggplot2
# Assign type to give
pdf(”[Link]", width=5, height=6) ggplot([Link](x = c(-3, 3)), aes(x = x))
jpeg(”[Link]", width=5, height=6) + stat_function(fun = pnorm)
png(”[Link]", width=5, height=6)
# plot and save
plot(readData$Height, col="blue”)
[Link]()

FES - Predictive Society and Data Analytics Lab 25


Programming in R: Plotting Example

FES - Predictive Society and Data Analytics Lab The data taken from 26
[Link]
Programming in R: Plotting Example

FES - Predictive Society and Data Analytics Lab The data taken from 27
[Link]
Programming in R: Plotting Example
• Built-in color options in R

FES - Predictive Society and Data Analytics Lab 28


Programming in R: Plotting Example

FES - Predictive Society and Data Analytics Lab 29


Programming in R: Plotting Example

FES - Predictive Society and Data Analytics Lab The data taken from 30
[Link]
Programming in R: Plotting Example

FES - Predictive Society and Data Analytics Lab The data taken from 31
[Link]
Programming in R: Plotting Example

FES - Predictive Society and Data Analytics Lab The data taken from 32
[Link]
Programming in R: Plotting Example

FES - Predictive Society and Data Analytics Lab The data taken from 33
[Link]
Getting Started with R

• What is R?
• What can you do in R?
• Installing R & R Studio
Overview •

RStudio IDE
Help and Navigation
• Installing Packages

Programming in R

• Basic Operations
• Basic Object Types
• Data Structures
• Control structures
• User-defined Functions
• I/O
• Useful build-in Functions
• Plotting

Probability and Statistics in R

• Sampling
• Distributions
• Statistical Tests
FES - Predictive Society and Data Analytics Lab 34
Probability and Statistics in R: Sampling
• Sampling from normal distribution
• Sampling from distribution
example
# Sampling without replacement
R <- 10
D <- rnorm(50) # Random normal
• We can use the following distribution
sampled <- sample(D, R) # By default replace=F
functions to generate a random
sample from common # Sampling with replacement
distributions such as normal, chi- R <- 10
D <- rnorm(50, 5, 2) # Random normal
squared, poisson, etc
distribution with mean = 5 and sd = 2
sampled <- sample(D, R, replace=T)
sampled
• Use “?rnorm” for details
FES - Predictive Society and Data Analytics Lab 35
Probability and Statistics in R: Distributions
• Each Distribution has functions with
p, q, d and r for the following
• p for "probability", the cumulative distribution
function (c. d. f.)
• q for "quantile", the inverse c. d. f.
• d for "density", the density function (p. f. or
p. d. f.)
• r for "random", a random variable having the
specified distribution

# Most common random distribution functions


rnorm, runif, rpois, rmvnorm, rnbinom, rbinom, rbeta,
rchisq, rexp, rgamma, rlogis, rstab, rt, rgeom, rhyper,
rwilcox, rweibull
FES - Predictive Society and Data Analytics Lab 36
Probability and Statistics in R: Table Lookup
• Looking up Normal and Standard • Looking up Chi-Square and Student-
Normal Curves T Distributions
# Normal distribution look up for any mean and # Chi-square look up
sd qchisq(.95, df=7)
dnorm(27.4, mean=50,sd=20) # P(X=27.4) pf
pnorm(27.4, mean=50, sd=20) # P(X<27.4) cdf # Student-t Lookup
qnorm(0.95, mean=100, sd=15) # inverse look up qt(.975, df=5)

# Standard Normal look up, same function


without mean, sd
dnorm(x)
pnorm(x)
qnorm(p)

FES - Predictive Society and Data Analytics Lab 37


Probability and Statistics in R: Statistical Tests
# Student´s T-Test
[Link](x, y = NULL, alternative = c("[Link]", "less", "greater"), mu = 0, paired = FALSE, …)
# Wilcoxon Test
[Link](x, y = NULL, alternative = c("[Link]", "less", "greater"), mu = 0, paired = FALSE, exact =
NULL, …)
# Shapiro-Wilk Test
[Link](x)
# Kolmogorov-Smirnov Test
[Link](x, y, …, alternative = c("[Link]", "less", "greater"), exact = NULL, …)
# Pearson's Chi-squared Test
[Link](x, y = NULL, correct = TRUE, p = rep(1/length(x), length(x)))
# Correlation Test
[Link](x, y, alternative = c("[Link]", "less", "greater"), method = c("pearson", "kendall",
"spearman"), exact = NULL, [Link] = 0.95, continuity = FALSE, …)

FES - Predictive Society and Data Analytics Lab 38


Probability and Statistics in R: Example

FES - Predictive Society and Data Analytics Lab 39


Final Notes
• Learn more on R by referring to
Mathematical Foundations of Data
Science Using R
• Available in TAU library
• For question regarding the video
• [Link]@[Link]
• The slides are based on content from
book and Aliyu Musa's Tutorial on R

FES - Predictive Society and Data Analytics Lab 40

You might also like