0% found this document useful (0 votes)
1 views60 pages

STTN215 Rslides2019

The document is a comprehensive guide to R programming, covering its introduction, data types, operators, functions, probability distributions, and programming techniques. It includes resources for learning R, instructions for data handling, and examples of basic functions and loops. The content is structured into several parts, making it suitable for beginners to understand the essentials of R programming.

Uploaded by

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

STTN215 Rslides2019

The document is a comprehensive guide to R programming, covering its introduction, data types, operators, functions, probability distributions, and programming techniques. It includes resources for learning R, instructions for data handling, and examples of basic functions and loops. The content is structured into several parts, making it suitable for beginners to understand the essentials of R programming.

Uploaded by

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

STTN215: First R class

2019

Compiled by Prof. Leonard Santana


Content
 PART I: INTRODUCTION
 What is R
 How to get R and R studio
 Basic interface of R and R studio
 PART II: DATA
 Data types in R
 Reading in data
 PART III: OPERATORS & FUNCTIONS
 Basic
 Mathematical
 Statistical
 PART IV: PROBABILITY DISTRIBUTIONS
 Probability functions
 Quantile functions
 Random number generation
 PART V: PROGRAMMING IN R
 Writing your own functions
 Writing "FOR" loops
 Writing "IF" statements
PART I: INTRODUCTION
Internet resources
 [Link] (The main R page)
 [Link] (The R Studio page)
 [Link] (The R-
Evolution page)

 Youtube video tutorials:


 [Link]
 [Link]
 [Link]
 [Link]

Search on YouTube; there are literally hundreds of these tutorials there.


These are just the first few that came up when I searched for "R tutorial".
Some are good, others… not so good.
What is R?
 R is a system for statistical computation and graphics
 It is free software distributed under a GNU-style copyleft
 R home page: [Link]

 The name is partly based on the (first) names of the first


two R authors (Robert Gentleman and Ross Ihaka),
 and partly a play on
the name of the Bell
Labs language ‘S’
What is CRAN?
 The “Comprehensive R Archive Network” (CRAN) is a
collection of sites which carry identical material,
consisting of the R distribution(s), the contributed
extensions, packages, documentation for R, and
binaries.

 [Link] (University of Cape Town)


 [Link] (TENET, Johannesburg)
Getting R
 Download R from:
[Link]

 Download Rstudio (a "wrapper" for R) at:


[Link]

 Download Revolution (a proprietary wrapper ) at:


[Link]
(Microsoft R Open 3.2.5 & MKL)
A first look at R (basic R)

The script window. Open by clicking


"File" , "New Script".
Run selected text by pressing "Ctrl+R"
The Console
Window.
Workspace: contains
A first look at R Studio all variables and their
values.

Plot
The script window. window.
Run selected text by clicking "Run" or pressing
"Ctrl+Enter"

The Console
Window.
Getting help in R
 Simply type "?" followed by the name of a
function to get help on a particular, known
function, e.g., to get help on the variance function
type:
?var

 Type "??" followed by a name to do a fuzzy search


for something that a function can do. For example,
to find a function related to "regression", type:
??"regression"
PART II: DATA
General notes
 R is case sensitive.
 Assign values to variables using "=" or "<-" or "->".
 For example, all three commands below assign the
value 768 to the variable X:

X = 768

X <- 768

768 -> X
Data types in R
 Scalars
 Vectors
 Matrices
 Lists
 Data frames
Data types in R
 Scalars (just 1 × 1 vectors):
B <- 192.90

 Vectors: Create these with the "c()" function:


D <- c(12,34,45)

 Matrices: Create these with the "matrix()" function:


G <- matrix(c(1,2,3,4,5,6),ncol=3,byrow=TRUE)

 Lists: Basically a vector that can have anything as its


elements. Create these with the "list()" function:
I <- list(X, D, G)
Data types in R
 Data frames: A data frame is used for storing data tables.
It is a list of vectors of equal length.

 Create with the "[Link]()" function:


L<-[Link](Xdat=c(1,2,3), Ydat=c(22,33,44))
Indexing in R (most common types)
 Vector indexing (one index only, e.g., […] ):
D[2] , D[1:2]
 Matrix indexing (two indices, e.g., [… , …] ):
G[2,3] , G[2,], G[,3]
 List ($ indexing and [[…]] indexing):
I$X , I[[2]]
 Data frames (all of the above types of indexing) :
L$Ydat , L[1,2] , L[[2]] , L[2]

 Special: Logical indexing (Indices are TRUEs and FALSEs):


D[D>20]
Reading data into R (.txt file)
 Use "[Link]" to get a text file into R.
data1 <- [Link]("[Link]",header=TRUE)

 The "header=TRUE" option is used above because


the data file contains variable names.
 If the data does not start on the first line we can also
use the "skip=" option.
 We will use this to specify how many lines to skip in the
file before it reaches "data".
 If it does not contain an absolute path, the file name is
relative to the current working directory, getwd()
Interactive way to load files in R
 Use "[Link]()" to open a "file picker" in R so you
can search through your directories to pick a file.
 For example, type

MyFile <- [Link]()


tmp <- [Link](MyFile)

Or simply

tmp <- [Link]( [Link]() )


OPERATORS & FUNCTIONS
Basic operators in R
 + Addition
 - Subtraction
 * Multiplication
 / Division
 ^ or ** Exponent
 %*% Matrix multiplication
 %/% Integer division
 %% Modulus (Remainder from division)
 t(⋅) Transpose of a matrix or vector
 solve(⋅) Inverse of a square matrix
 %in% Determines if one thing is an element of another
 : Sequence
Basic operators in R

What happens when you apply these operators to a


matrix, vector, scalar, data frame or list?
Basic mathematical functions in R
 abs(arg) Calculates the absolute value of the arg
 exp(arg) Calculates 𝑒 to the power of arg
 gamma(arg) Evaluates the gamma function in arg
 log(arg) Determines the natural log of arg
 log10(arg) Determine the log to base 10 of arg
 sign(arg) Determines the sign of arg
 sqrt(arg) Determines the square root of arg
 cos(arg) Determine the cosine of arg
 sin(arg) Determine the sine of arg
 tan(arg) Determine the tangent of arg
Basic statistical functions in R
• sum(arg) Calculates the sum of arg
• mean(arg) Calculates the mean of arg
• median(arg) Calculates the median of arg
• var(arg) Calculates the variance of arg
(or covariance if more than one
argument)
• sd(arg) Calculates the standard deviation of
arg
• cor(arg1,arg2) Calculates the correlation between
arg1 and arg2
• min(arg), max(arg) Calculates the min, max of arg
• quantile(arg,p) Calculates the pth percentile of arg
• sample(arg) Draws a random sample from arg
Basic matrix functions in R
 rbind(arg1,arg2) Appends the row vector arg2 to the matrix arg1
 cbind(arg1,arg2) Appends the column vector arg2 to the matrix arg1
 t(arg) Transposes the matrix arg
 eigen(arg) Calculates the Eigen-values and Eigen-vectors of arg
 diag(arg) Creates a matrix with the vector arg as the diagonal
elements
 diag(arg) Extracts the diagonal components of the matrix arg
 solve(arg) Finds the inverse of the square non-singular matrix arg
 svd(arg) Determines the singular value decomposition of a matrix
arg
 chol(arg) Determines the Cholesky decomposition of a square,
symmetric, positive definite matrix arg
Basic data functions in R
 length(arg) Returns the length of the vector arg
 dim(arg) Returns the dimensions of arg
 ncol(arg) Returns the number of columns of arg
 nrow(arg) Returns the number of rows of arg
 names(arg) Returns the names of arg (for lists and
data frames)
 dimnames(arg) Returns the names of arg (for matrices and
data frames)
Basic data functions in R
• matrix(arg1,ncol=arg2) Creates a matrix from vector
arg1 and number of
columns arg2 .
• [Link](arg) Creates a data frame from
the matrix arg.
• array(arg1,arg2) Creates a multidimensional
array vector arg1 and
dimensions arg2 .
• complex(real,im) Creates a complex number
with real and imaginary part.
PROBABILITY DISTRIBUTIONS

28
Probability functions in R
 R has a rather neat way of dealing with…
 the probability distribution functions
 probability density functions
 quantile functions
 random number generator functions
 …for various distributions.

29
Probability functions in R
 All probability distribution functions start with "p".
 All density or mass functions start with "d".
 All quantile functions start with "q".
 All random number generators functions start with
"r".

30
Probability functions in R
R's code for the Parameters Distribution
distribution
norm mu, sigma Normal distribution

exp lambda Exponential distribution

t df 𝑡 distribution

f df1, df2 𝐹 distribution

chisq Df 𝜒 2 distribution

unif a, b Uniform distribution

binom size, prob Binomial distribution

pois lambda Poisson distribution

31
Probability functions in R
 For example, suppose that 𝑋 ∼ 𝑁 0 , 92 , with
distribution function 𝐹 𝑥 = 𝑃(𝑋 < 𝑥) and density
function 𝑓(𝑥).
 To determine 𝐹 2.9 = 𝑃(𝑋 < 2.9) we type:
pnorm(2.9,0,9)
 To determine 𝑓(2.9) we type:
dnorm(2.9,0,9)
 To determine 𝐹 −1 (0.95) we type:
qnorm(0.95,0,9)
 To generate 1000 observations from 𝑋 type:
rnorm(1000,0,9)
32
Probability functions in R
 If W ~ Poisson(lambda=1.5) then 𝑃(𝑊 <= 4) is:
ppois(4,1.5)

 If W ~ Poisson(lambda=1.5) then 𝑃(𝑊 = 4) is:


dpois(4,1.5)

 If W ~ Poisson(lambda=1.5) then 𝐹 −1 (0.5) is:


qpois(0.5,1.5)

 Randomly draw 5 values from W ~ Poisson(lambda=1.5):


33
rpois(5,1.5)
PROGRAMMING IN R
Basic Function Writing

34
Basic function writing
 To write a function simply use the
"function()" function.
 Assign the function to a variable.
 Use "{" and "}" brackets for grouping commands.
 Write your code between the "{" and "}"
brackets.
 Return an answer using either
 the "return()" function or
 by simply typing the output variable as the last line of
the function.

35
Basic function writing
Fixed syntax code
The name of the words for a function. Variables used for input
function. (separated by commas).

funcName <- function(input){


…code…
return(outputVariable)
}
Variable that is output
by the function.

36
Basic function writing
Fixed syntax code
The name of the words for a function. Variables used for input
function. (separated by commas).

funcName <- function(input){


…code…
outputVariable
}
Variable that is output by the
function. Simply type it as the last line
of the function.

37
Basic function writing
 For example, to write a function to calculate the
square of a value, x, use:
MyFun1 <- function(x){
ans <- x^2
return(ans)
}
 To use the function, simply "call" it as follows:
MyFun1(2)

38
Basic function writing
(multiple arguments)

 Another example: write a function to calculate the


yth power of a value, x:
MyFun2 <- function(x,y){
ans <- x^y
return(ans)
}
 To use the function, simply "call" it as follows:
MyFun2(2,9)

39
Basic function writing
(Returning multiple values)
 Another example: write a function to calculate the yth
power of a value, x and also calculate the product of
these two numbers:
MyFun3 <- function(x,y){
ans1 <- x^y
ans2 <- x*y
ans <- list(ans1,ans2)
return(ans)
}
 To use the function, simply "call" it as follows:
MyFun3(2,9)

40
PROGRAMMING IN R
Iteration and "for" loops

41
Loops
 When writing a "for" loop you need to specify:
 the index for counting and
 a vector that contains the potential values in the loop:

for(index in vector)
Vector of values that
Fixed syntax code
index can assume.
words for a "for" Variable that can be
loop. reused in the loop;
changes values on each
iteration. Assumes the
values listed in vector.
42
Loops
 Examples of "for" loops:

for(i in c(1,2,3)){
print(i)
}
or
for(j in 1:3){
print(j)
}
or
for(k in 5:9){
print(k)
}

43
Loops
 Here's a generic function for the loops on the previous
slide:
LoopFunc <- function(start,end){
for(i in start:end){
print(i)
}
}

LoopFunc(4,9)

44
Note:

 R remembers all the variables you create, which


can sometimes cause problems.
 Good practice is to clear out all the old variables
defined previously so you don't run into these
issues.
 Type the following to delete all old variables (I
usually add this line at the top of all my programs):

rm(list=ls())
PROGRAMMING IN R
Conditional statements: "if-else"

46
If statements
 If statements:
X <- 12
if(X > 8){
print("X larger than 8")
}

47
If-else statements
 If-else statements (1):
X <- 3
if(X > 8){
print("X larger than 8")
} else {
print("otherwise")
}

48
If-else statements
 If-else statements (2):
X <- 3
if(X > 8){
print("X larger than 8")
} else if (X <= 8){
print("X smaller than 8")
} else {
print("otherwise")
}

49
If statements: Logical operators
Operator What it does

< Less than

> Greater than

<= Less than or equal to

>= Greater than or equal to

!= Not equal to

== Is equal to

& Elementwise AND

| Elementwise OR

50
Exercises - A
1. Create vectors called "Score" and "Grade" which are equal to:
92.8 9
47.6 8
𝑆𝑐𝑜𝑟𝑒 = 84.2 and 𝐺𝑟𝑎𝑑𝑒 = 10 .
88.1 8
73.1 10

2. Create a matrix called "DesignMatrix" which is equal to:


1 12 23
1 44 30
𝐷𝑒𝑠𝑖𝑔𝑛𝑀𝑎𝑡𝑟𝑖𝑥 = 1 12 45 .
1 20 82
1 10 70
Exercises - A
3. Create a data frame called "VecData" which contains the
vectors "Score" and "Grade" as its columns:

Score Grade
92.8 9
47.6 8
84.2 10
88.1 8
73.1 10
Exercises - A
4. Use the data stored in the file "[Link]".
a) Read this data into a data frame named "MyData".

Xdat Ydat
1 12
2 23
3 34
4 45
5 56
6 67
7 78

b) Change the names of the columns to "𝑆𝑡𝑢𝑑𝑒𝑛𝑡𝑁𝑜" and


"𝑃𝑒𝑟𝑐𝑒𝑛𝑡".
Exercises - A
12 11
12 1 2
45 46
15 2 2.5
5. Let 𝒁 = 23 , 𝒀 = 27 , and 𝑾 =
17 −1 3.9
10 10
22 1 4.1
26 25

a) Calculate the standard deviation of the data in 𝒁.


b) Calculate the length of 𝒀 (call this 𝑛).
c) Calculate the mean of each of the columns of 𝑾.
Exercises - B
1. Calculate 𝑃(𝑊 < 1.8), where 𝑊 ∼ 𝑁(1,2).
2. Calculate the value of 𝑥 if 𝑃 𝑋 < 𝑥 = 0.3, where 𝑋 ∼ 𝜒42 .
3. Calculate 𝑃 𝑌 > 2 , where 𝑌 ∼ 𝑡19 .
4. Calculate the value of 𝑧 if 𝑃 𝑍 > 𝑧 = 0.9, where 𝑍 ∼ 𝐹2,3 .
5. Calculate the probability that you get exactly 3 "heads" out of 10
tosses of a fair coin.
6. Generate 100 observations from an 𝐸𝑥𝑝(𝜆 = 3) distribution and
calculate the sample mean of these observations. Compare this
to the expected value of an 𝐸𝑥𝑝(𝜆 = 3) distribution. Now
generate 1 000 000 observations and calculate the sample mean
again. Compare the answers.

55
Exercises - B
7. A multiple choice question paper consists of 20
questions, each with four choices. A student is able to
eliminate one of the choices at each question, and then
must randomly choose one of the three remaining
options. The student must get 12 or more questions
correct in order to pass. What is the probability that the
student passes if she randomly chooses in this way?
8. The average number of traffic accidents on the N12
between Potchefstroom and Johannesburg is 2 per
week. Assume that the number of accidents in a week
follow a Poisson distribution with 𝜆=2.
Calculate the probability that no accidents occur between
Potch and Johannesburg during a 1-week period.
56
Exercises - C
 Write a function called MyFirstFunc that
 Takes as argument a data vector called
Xdata,
 Calculates the length, sum, and mean of this
vector, and
 Returns these three values in a list.

 Use the data 𝑋 = {10,15,20,25,30} to test the


function.
 The function should return length=5, sum=100,
and mean=20
57
Exercises - C
 Create a vector called Y that contains 10 zeros. Use
the "repeat" function "rep" as follows:
Y <- rep(0,10)
 Write a loop that starts at 1 and goes to 10 (use the
index i).
 At each iteration, calculate the value
𝑖 2 , 𝑖 = 1,2, … , 10
 Store each value calculated in the 𝑖th position of Y.
 Next, use this to calculate
10

෍ 𝑖2
𝑖=1
 Can you write the loop to do this in a different way?
58 i.e., without having to first define a vector Y.
Exercises - D
Monte Carlo approximation of sampling distribution of the mean
Write a function called ExFunc1 that:
 Takes two arguments called MC and n.
 In each step of a loop from 1 to MC:
 Generate n observations from a 𝑁(𝜇 = 10, 𝜎 2 = 9) distribution .
Call this X.
ത the sample mean, for this generated sample.
 Calculate 𝑋,
 Store this statistic value for each iteration of the loop in a vector.
 Calculate and return the mean and variance of the MC 𝑋 ത values
calculated above.
 State what you think the expected value and variance of 𝑋 ത should
be.
ത values (use
 Optional: Plot the histogram of all the calculated 𝑋
the "hist()" function).
59
Exercises - D
 Write a function that takes 𝑋 and 𝛼 as
arguments and calculates the following:
 Let 𝑋 ∼ 𝑁(𝜇𝑋 , 𝜎𝑋2 ) 𝑋 , recorded
Use the data available and calculate annual losses (in
USD$) for 7
the following 1 − 𝛼 × 100% businesses
confidence interval for the population 145
mean annual losses, 𝜇𝑋 : 86
𝛼 195

𝑋 ± 𝑡𝑛−1 𝑆𝑋ത
2 155
with 𝛼 = 0.1 and where 92
1 𝑛 2 1

𝑋 = σ𝑖=1 𝑋𝑖 and 𝑆𝑋ത = σ𝑛𝑖=1 𝑋𝑖 − 𝑋ത 2 74
𝑛 𝑛(𝑛−1)
182

60

You might also like