0% found this document useful (0 votes)
8 views79 pages

R Programming

The document provides a comprehensive overview of various concepts in R programming, including basic data types, lists, special values, assignment operators, and functions for statistical analysis. It covers topics such as normal distribution, ANOVA, linear regression, file handling, and matrix operations, along with examples and syntax. Additionally, it discusses features of R programming, including its cross-platform compatibility and extensive community support.

Uploaded by

vefole2166
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
8 views79 pages

R Programming

The document provides a comprehensive overview of various concepts in R programming, including basic data types, lists, special values, assignment operators, and functions for statistical analysis. It covers topics such as normal distribution, ANOVA, linear regression, file handling, and matrix operations, along with examples and syntax. Additionally, it discusses features of R programming, including its cross-platform compatibility and extensive community support.

Uploaded by

vefole2166
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 79

Section-A

1 ) List the basic datatypes in R.


*Ans: Numeric, Integer, Complex, Logical,Character.

2) Define list in R. Write an example to create a list.


*Ans: In R, a list is a data structure that can store multiple values of different data types, including
numeric, character, logical, and other lists.
* Example to Create a List in R:
Here's an example to create a list in R:
# Create a list
my_list <- list(
name = "John Doe",
age = 30,
occupation = c("Software Engineer", "Data Scientist"),
skills = list(programming = c("R", "Python", "Java"),
languages = c("English", "Spanish")))
# Print the list
print(my_list)
Output:
$name
[1] "John Doe"
$age
[1] 30
$occupation
[1] "Software Engineer" "Data Scientist"
$skills
$skills$programming
[1] "R" "Python" "Java"
$skills$languages
[1] "English" "Spanish"
In this example, we created a list called my_list with four elements: name, age, occupation, and
skills. The skills element is itself a list with two elements: programming and languages.

3) what do you mean by special values ? Give example.


*Ans: In R, special values are values that have a specific meaning or behavior in certain contexts.
These values are not part of the standard numeric or character data types, but rather are used to
represent missing, infinite, or undefined values. Here are some examples of special values in R:
1. NA (Not Available): represents a missing or undefined value.
Example: x <- c(1, 2, NA, 4)
1. NaN (Not a Number): represents an invalid or unreliable numeric result.
Example: x <- 0/0 (results in NaN)

4) Mention the different assignment operatorS In R with examples.


*Ans: In R, there are several assignment operators that can be used to assign values to variables.
Here are the different assignment operators in R, along with examples:
1. Leftward Assignment Operator (<-)
Example: x <- 5 assigns the value 5 to the variable x.
1. Rightward Assignment Operator (->)
Example: 5 -> x assigns the value 5 to the variable x.
1. Equal Sign Assignment Operator (=)
Example: x = 5 assigns the value 5 to the variable x.
1. Combined Assignment Operators
- Addition Assignment Operator (+=)
*Example: x <- 5; x += 3 adds 3 to the value of x, resulting in x = 8.
5) Differentiate between cat () and Print () functions.
*Ans: In R, cat() and print() are two functions used to output text and values to the console. While
they may seem similar, there are key differences between them:
cat()
- cat() is a low-level output function that concatenates and prints objects.
- It does not automatically append a newline character at the end of the output.
- cat() does not print the object name or quotes around character strings.
- It is useful for generating output that needs to be formatted precisely.
print()
- print() is a generic function that prints its argument and returns it.
- It automatically appends a newline character at the end of the output.
- print() prints the object name and quotes around character strings.
- It is the default method used by R when printing objects.

6) Write the syntax of"while" and"repeat" statements in R.


*Ans: while (condition) {
# statements to be executed
}
repeat {
# statements to be executed
if (condition) {
brea }}

7) Write the purpose of prod () and round () functions. Give example for each.
*Ans: prod() Function
The prod() function calculates the product of all the elements in a numeric vector.
Example
# Create a numeric vector
x <- c(2, 3, 4)
product <- prod(x)
print(product) # Output: 24
round() Function
The round() function rounds a numeric value to the specified number of decimal places.
Example
# Create a numeric value
x <- 12.5678
rounded_x <- round(x, 2)
print(rounded_x) # Output: 12.57

8) List any four functions on set operations.


*Ans: union(), intersect(), setdiff(), setequal().

9) Define normal distribution.


*Ans: A normal distribution, also known as a Gaussian distribution or bell curve, is a probability
distribution that is symmetric about the mean, showing that data near the mean are more frequent
in occurrence than data far from the mean. In graph form, the normal distribution will appear as a
bell curve.

10) What is ANOVA? Write the notations for Null and alternative hypothesis.
*Ans: ANOVA (Analysis of Variance) is a statistical technique used to compare the means of two or
more groups to determine if there is a significant difference between them. It is commonly used to
analyze the effect of one or more categorical variables (factors) on a continuous outcome variable.
* - Null Hypothesis (H0): μA = μB
- This states that the means of the two groups are equal.
- Alternative Hypothesis (H1): μA ≠ μB
- This states that the means of the two groups are not equal.
11) Write the purpose and syntax of lm ( ) function in R.
*Ans: Purpose of lm() function:
The lm() function in R is used to fit a linear regression model to a dataset. It estimates the
relationship between a continuous outcome variable (response variable) and one or more predictor
variables (explanatory variables).

Syntax of lm() function:

The general syntax of the lm() function is:


lm(formula, data, subset, weights, na.action, method = "qr", model = TRUE, x = FALSE, y = FALSE, qr =
TRUE, singular.ok = TRUE, contrasts = NULL, offset, ...)

12) What are regions and margins in a R plot?


*Ans: Regions in a Plot
1. Plotting Region: This is the innermost region where the actual plot is drawn.
2. Figure Region: This is the entire area allocated for the plot, including the plotting region, margins,
and any surrounding labels or titles.

Margins in a Plot
1. Margins: These are the areas outside the plotting region but within the figure region. There are
four margins:
- Bottom Margin (or x-axis margin): below the plotting region.
- Left Margin (or y-axis margin): to the left of the plotting region.
- Top Margin: above the plotting region.
- Right Margin: to the right of the plotting region.
Section-B

13) Define vector in R. Explain the different ways of creating a vector.


*Ans: In R, a vector is a one-dimensional array of elements of the same data type, such as numeric,
character, or logical. Vectors are the most basic data structure in R and are used to store and
manipulate data.
*Ways of Creating a Vector in R:
*There are several ways to create a vector in R:
1. Using the c() Function:
The c() function is the most common way to create a vector in R. It combines values into a vector.
x <- c(1, 2, 3, 4, 5)
1. Using the colon Operator (:):
The colon operator can be used to create a vector of consecutive numbers.
x <- 1:5
1. Using the seq() Function:
The seq() function can be used to create a vector of numbers with a specified increment.
x <- seq(1, 5, by = 1)
1. Using the rep() Function:
The rep() function can be used to create a vector by repeating a value or a set of values.
x <- rep(1, 5)
1. Using Character Values:
Character vectors can be created using the c() function with character values enclosed in quotes.
x <- c("apple", "banana", "cherry")
7)--how the z - test useful in r programming
*Ans: The **Z-test** in R programming is useful for hypothesis testing, particularly when comparing
a sample mean to a known population mean or comparing the means of two independent samples,
especially when the sample size is large (n > 30) and the population standard deviation is known. It
helps determine whether observed differences are statistically significant, aiding decision-making in
data analysis.
14) What is recursion? Write an R program to fnd the factorial of a number using recursion.
*Ans: Recursion is a programming technique where a function calls itself repeatedly until it reaches a
base case that stops the recursion. In other words, a function solves a problem by breaking it down
into smaller instances of the same problem, which are then solved by the same function, until the
solution to the original problem is found.
R Program to Find the Factorial of a Number Using Recursion
*Here is an example of an R program that uses recursion to calculate the factorial of a given number:
# Define a recursive function to calculate the factorial
factorial <- function(n) {
# Base case: factorial of 0 or 1 is 1
if (n == 0 | n == 1) {
return(1)
}
# Recursive case: n! = n * (n-1)!
else {
return(n * factorial(n-1)) }
}
# Test the function
num <- 5
result <- factorial(num)
print(paste("The factorial of", num, "is", result))

15) What is a file? Explain any four file handling functions inR.
*Ans: A file is a collection of data stored on a computer's storage device, such as a hard drive, solid-
state drive, or flash drive. Files can contain various types of data, including text, images, audio,
video, and executable programs. Each file has a unique name and is stored in a specific location on
the computer, such as a folder or directory.
File Handling Functions in R
Here are four commonly used file handling functions in R:
1. read.table(): Reads a file in table format and returns a data frame.
Example: data <- read.table("data.txt", header = TRUE)
2. write.table(): Writes a data frame to a file in table format.
Example: write.table(data, "data.txt", row.names = FALSE)
3. file.exists(): Checks if a file exists.
Example: file.exists("data.txt")
4. file.remove(): Deletes a file.
Example: file.remove("data.txt")

16) Compute the mean and median for the following observations: (9,5,2,3,4,6.7) Mention the R
functions for the sanme.
*Ans: To compute the mean and median for the given observations, we can use the following R
functions:
Mean
The R function to calculate the mean is mean().
Median
The R function to calculate the median is median().
Here's how to use these functions:
# Given observations
x <- c(9, 5, 2, 3, 4, 6.7)
# Calculate mean
mean_x <- mean(x)
print(paste("Mean:", mean_x))
# Calculate median
median_x <- median(x)
print(paste("Median:", median_x))
When you run this code, it will output the mean and median of the given observations.
17) Write a note on simple linear regression.
*Ans: Simple linear regression is a statistical method used to model the relationship between a
dependent variable (y) and a single independent variable (x). The goal is to create a linear equation
that best predicts the value of y based on the value of x.
Assumptions:
1. Linearity: The relationship between x and y is linear.
2. Independence: Each observation is independent of the others.
3. Homoscedasticity: The variance of the residuals is constant across all levels of x.
4. Normality: The residuals are normally distributed.
5. No multicollinearity: The independent variable is not highly correlated with itself.
Equation:
The simple linear regression equation is:
y = β0 + β1x + ε
where:
- y is the dependent variable
- x is the independent variable
- β0 is the intercept or constant term
- β1 is the slope coefficient
- ε is the error term
Section-C
18) a. Discuss the features of R programming.
Ans: *Cross-Platform Compatibility:
R is available on multiple platforms, including Windows, macOS, and Linux.
*Large Community and Support:
R has a large and active community of users, developers, and contributors. Users can seek help and
support through various online forums, mailing lists, and documentation.
*Extensive Documentation and Resources:
R has extensive documentation and resources, including the official R documentation, online
tutorials, books, and courses.
*Integration with Other Tools and Languages:
R can be easily integrated with other tools and languages, including Python, SQL, and Excel.
*Open-Source and Free:
R is open-source and free, making it accessible to users worldwide.

b) Explain the different algebraic operations on matrices.


Ans: Addition and Subtraction
- Matrix Addition: Two matrices A and B can be added if they have the same dimensions. The
resulting matrix C is obtained by adding corresponding elements of A and B.
C=A+B
- Matrix Subtraction: Two matrices A and B can be subtracted if they have the same dimensions. The
resulting matrix C is obtained by subtracting corresponding elements of A and B.
C=A-B
Multiplication
- Scalar Multiplication: A matrix A can be multiplied by a scalar k. The resulting matrix B is obtained
by multiplying each element of A by k.
B = kA
- Matrix Multiplication: Two matrices A and B can be multiplied if the number of columns in A is
equal to the number of rows in B. The resulting matrix C is obtained by multiplying the rows of A by
the columns of B.
C = AB
Transpose
- Transpose: The transpose of a matrix A, denoted by A^T or A', is obtained by interchanging the
rows and columns of A.
Inverse
- Inverse: The inverse of a square matrix A, denoted by A^(-1), is a matrix that satisfies the property
AA^(-1) = A^(-1)A = I, where I is the identity matrix.
19) a. Define variance, Covariance and correlation.
Ans: Variance is a measure of the spread or dispersion of a set of data from its mean value. It
represents how much the individual data points deviate from the average value. The variance is
calculated as the average of the squared differences between each data point and the mean.
Formula: σ² = Σ(xi - μ)² / (n - 1)
where σ² is the variance, xi is each data point, μ is the mean, and n is the number of data points.
*Covariance
Covariance is a measure of the linear relationship between two continuous variables. It represents
how much the variables move together. If the covariance is positive, it means that as one variable
increases, the other variable also tends to increase. If the covariance is negative, it means that as
one variable increases, the other variable tends to decrease.
*Formula: Cov(X, Y) = Σ[(xi - μx)(yi - μy)] / (n - 1)
where Cov(X, Y) is the covariance between variables X and Y, xi and yi are individual data points, μx
and μy are the means of X and Y, and n is the number of data points.
*Correlation
Correlation is a measure of the strength and direction of the linear relationship between two
continuous variables. It is a dimensionless quantity that ranges from -1 to 1. A correlation of 1 means
a perfect positive linear relationship, while a correlation of -1 means a perfect negative linear
relationship. A correlation of 0 means no linear relationship.
*Formula: ρ = Cov(X, Y) / (σx * σy)
where ρ is the correlation coefficient, Cov(X, Y) is the covariance between X and Y, and σx and σy are
the standard deviations of X and Y.

b)Write a R program to illustrate plot () list () and Pie () plotting functions.


Ans: Here's an example R program that illustrates the use of the plot(), lines(), and pie() plotting
functions:
# Create a sample dataset
x <- c(1, 2, 3, 4, 5)
y <- c(2, 4, 6, 8, 10)
# Plot the data using plot()
plot(x, y, type = "b", main = "plot() function",
xlab = "X-axis", ylab = "Y-axis")
# Add a line to the plot using lines()
lines(x, y + 2, col = "red", lwd = 2)
# Create a sample dataset for pie chart
labels <- c("A", "B", "C", "D")
sizes <- c(25, 30, 20, 25)
# Plot the data using pie()
pie(sizes, labels = labels, main = "pie() function",
col = c("red", "green", "blue", "yellow"))

7—What is a 3D scatter plot ?


*Ans: A **3D scatter plot** in R programming is a graphical representation of data points in three-
dimensional space, displaying relationships between three variables. It helps visualize complex data
structures and patterns by plotting data points along the x, y, and z axes. The **`plot3d`** function
from the **`rgl`** package is commonly used to create 3D scatter plots in R.

8—Define linear regression.


**Linear regression** in R programming is a statistical method used to model the relationship
between a dependent variable and one or more independent variables by fitting a linear equation.
The **`lm()`** function in R is used to perform linear regression, where the model predicts the
dependent variable based on the values of the independent variables.
20) a. Explain the concept of Markov chain with a suitable example.
Ans: A Markov chain is a mathematical system that undergoes transitions from one state to another,
where the probability of transitioning from one state to another is dependent solely on the current
state and time elapsed. The future state of the system is determined solely by its current state, and
not by any of its past states.
Example: Weather Forecasting
Consider a simple weather forecasting model that predicts the weather for the next day based on
the current weather. Let's say we have three possible weather states: Sunny (S), Cloudy (C), and
Rainy (R).
The probability of transitioning from one weather state to another is as follows:
| Current Weather | Probability of Next Day's Weather |
| --- | --- |
| S | S: 0.7, C: 0.3, R: 0.0 |
| C | S: 0.4, C: 0.5, R: 0.1 |
| R | S: 0.1, C: 0.3, R: 0.6 |
For example, if the current weather is Sunny (S), there is a 70% chance that the next day's weather
will be Sunny (S), a 30% chance that it will be Cloudy (C), and a 0% chance that it will be Rainy (R).

b) Discuss the following:


i) Defining colors in R plots
A: In R, colors can be defined in various ways to customize plots.
Metods are:
Named colors, Hexadecimal Colors, RGB Colors, RGBA Colors, Color Palettes.
ii) Point and click co-ordinate interaction.
A: In R, you can use the locator() function to enable point-and-click coordinate interaction. This
function allows you to click on a plot and returns the coordinates of the clicked point.
Here's an example:
# Create a plot
plot(1:10, 1:10, type = "n")
# Enable point-and-click interaction
coords <- locator()
# Print the coordinates of the clicked point
print(coords)
In this example, the locator() function is used to enable point-and-click interaction on the plot. When
you click on the plot, the coordinates of the clicked point are returned and stored in the coords
variable.
STATISTICS WITH R PROGRAMMING Unit - 2

R Programming Structures: Control Statements - Loops, Looping Over Non-vector Sets, If-Else,
Arithmetic and Boolean Operators and values, Default Values for Argument, Return Values -
Deciding Whether to explicitly call return, Returning Complex Objects, Functions are Objective, No
Pointers in R, Recursion - A Quick sort Implementation, Extended Extended Example: A Binary
Search Tree.

Control Statements: The statements in an R program are executed sequentially from the top of the
program to the bottom. But some statements are to be executed repetitively, while only executing other
statements if certain conditions are met. R has the standard control structures.

Loops: Looping constructs repetitively execute a statement or series of statements until a condition isn‘t
true. These include the for, while and repeat structures with additional clauses break and next.
1) FOR :- The for loop executes a statement repetitively until a variable‘s
value is no longer contained in the sequence seq.
 The syntax is for (var in sequence)
{
statement
}
Here, sequence is a vector and var takes on each of its value
during the loop. In each iteration, statement is evaluated.
 for (n in x) { - - - }
It means that there will be one iteration of the loop for each
component of the vector x, with taking on the values of those
components—in the first iteration, n = x[1]; in the second
iteration, n = x[2]; and so on.
 In this example for (i in 1:10) print("Hello") the word Hello is
printed 10 times.
 Square of every element in a vector:
> x <- c(5,12,13)
> for (n in x) print(n^2)
[1] 25
[1] 144
[1] 169

 Program to find the multiplication


# take input from the user
num = as.integer(readline(prompt = "Enter a number: "))
# use for loop to iterate 10 times
for(i in 1:10) {
print(paste(num,'x', i, '=', num*i)) }

2) WHILE:- A while loop executes a statement repetitively until the


condition is no longer true.
Syntax:
while (expression)
{
statement
}
 Here, expression is evaluated and the body of the loop is entered if
the result is TRUE.
STATISTICS WITH R PROGRAMMING Unit - 2

 The statements inside the loop are executed and the flow returns to evaluate
the expression again.
 This is repeated each time until expression evaluates to FALSE, in which case, the loop exits.
 Example
> i <- 1
> while (i<=10) i <- i+4
>i
[1] 13

 Program to find the sum of first n natural numbers


sum = 0
# take input from the user
num = as.integer(readline(prompt = "Enter a number: ")) Output:
# use while loop to iterate until zero Enter a number: 4
while(num > 0) [1] "The sum is 10"
{
sum = sum + num
num = num - 1
}
print(paste("The sum is", sum))

3) Break statement: A break statement is used inside a loop


(repeat, for, while) to stop the iterations and flow the control outside of
the loop.In a nested looping situation, where there is a loop inside
another loop, this statement exits from the innermost loop that is being
evaluated.
Syntax:- break
Example
x <- 1:5
Output:
for (val in x) {
[1] 1
if (val == 3){
[1] 2
break
}
print(val)
}

4) Next statement:- A next statement is useful when we want to skip the


current iteration of a loop without terminating it. On encountering next,
the R parser skips further evaluation and starts next iteration of the loop.
Syntax:- next
Example
x <- 1:5
for (val in x) { Output:
if (val == 3){ [1] 1
next [1] 2
} [1] 4
print(val) [1] 5
}

5) Repeat:- Repeat loop is used to iterate over a block of code multiple number of times. There is no
condition check in repeat loop to exit the loop.
STATISTICS WITH R PROGRAMMING Unit - 2

We must ourselves put a condition explicitly inside the body of the loop and use the break statement to
exit the loop. Failing to do so will result into an infinite loop.

Syntax:
repeat
{
statement
}

Example:

x <- 1
repeat Output:
{ [1] 1
print(x) [1] 2
x = x+1 [1] 3
if (x == 6) [1] 4
break [1] 5
}

Looping Over Non-vector Sets:- R does not directly support iteration over nonvector sets, but there
are a couple of indirect yet easy ways to accomplish it:
 apply( ):- Applies on 2D arrays (matrices), data frames to find aggregate functions like
sum, mean, median, standard deviation.
syntax:- apply(matrix,margin,fun, ..... )
margin = 1 indicates row
= 2 indicates col
> x <- matrix(1:20,nrow = 4,ncol=5)
>x
[,1] [,2] [,3] [,4] [,5]
[1,] 1 5 9 13 17
[2,] 2 6 10 14 18
[3,] 3 7 11 15 19
[4,] 4 8 12 16 20
> apply(x,2,sum)
[1] 10 26 42 58 74

 Use lapply( ), assuming that the iterations of the loop are independent of each other, thus
allowing them to be performed in any order. Lapply( ) can be applies on dataframes,lists
and vectors and return a list. lapply returns a list of the same length as X, each element of
which is the result of applying FUN to the corresponding element of X.
Syntax: lapply(X, FUN, ...)
> x <- matrix(1:4,2,2)
>x
[,1] [,2] lapply( ) function is applied on every
[1,] 1 3 elements of the object.
[2,] 2 4
> lapply(x,sqrt)
[[1]]
[1] 1

[[2]]
[1] 1.414214

[[3]]
[1] 1.732051
STATISTICS WITH R PROGRAMMING Unit - 2

[[4]]
[1] 2
 Use get( ), As its name implies, this function takes as an argument a character string
representing the name of some object and returns the object of that name. It sounds simple,
but get() is a very powerful function.
Syntax: get(“character string”)
> get("sum")
function (..., na.rm = FALSE) .Primitive("sum")
> get("g")
function(x)
{
return(x+1)
}
> get("num")
[1] "45"

Note:- Reserved words in R programming are a set of words that have special meaning and cannot be
used as an identifier (variable name, function name etc.).This list can be viewed by
typing help(reserved) or ?reserved at the R command prompt.

Reserved words in R

If else repeat while function

for in next break TRUE

FALSE NULL Inf NaN NA

NA_integer_ NA_real_ NA_complex_ NA_character_ ...

If –Else:- The if-else control structure executes a statement if a given condition is true. Optionally, a
different statement is executed if the condition is false.
The syntax is
if (cond) if (cond)
{ {
statements statement1
} } else
{
statement2
}
STATISTICS WITH R PROGRAMMING Unit - 2

x <- 8
if(x>3) {y <- 10 Output:
} else {y<-0} [1] 10
print(y)

y <- ifelse(x>3, 10, 0)


y Output:
[1] 0
x <- 4
if(x==4) Output: Error.
x <- 1
else
The right brace before the else is used by the R parser to
{ deduce that this is an if-else rather than just an if.
x <- 3
y <- 4
}

An if-else statement works as a function call, and as such, it returns the last value assigned.
v <- if (cond) expression1 else expression2
This will set v to the result of expression1 or expression2, depending on whether cond is true. You
can use this fact to compact your code. Here‘s a simple example:
> x <- 2
> y <- if(x == 2) x else x+1
>y
[1] 2

> x <- 2
>if(x == 2) y <- x else y <- x+1
>y
[1] 2

Operators:- R has many operators to carry out different


mathematical and logical operations.
Types of operators
1. Arithmetic operators.
2. Relational operators.
3. Logical operators.
4. Assignment operators.
5. Miscellaneous Operators

1. Arithmetic operators:- These operators are used to carry out mathematical operations like addition
and multiplication. Here is a list of arithmetic operators available in R.
Operator Description Example

v <- c( 2,5.5,6)
t <- c(8, 3, 4)
+ Adds two vectors print(v+t)
it produces the following result −
[1] 10.0 8.5 10.0

v <- c( 2,5.5,6)
Subtracts second t <- c(8, 3, 4)

vector from the first print(v-t)
it produces the following result −
STATISTICS WITH R PROGRAMMING Unit - 2

[1] -6.0 2.5 2.0

v <- c( 2,5.5,6)
t <- c(8, 3, 4)
Multiplies both print(v*t)
*
vectors
it produces the following result −
[1] 16.0 16.5 24.0

v <- c( 2,5.5,6)
t <- c(8, 3, 4)
Divide the first vector
/ print(v/t)
with the second
When we execute the above code, it produces the following result −
[1] 0.250000 1.833333 1.500000

v <- c( 2,5.5,6)
Give the remainder of t <- c(8, 3, 4)
%% the first vector with print(v%%t)
the second it produces the following result −
[1] 2.0 2.5 2.0

v <- c( 2,5.5,6)
The result of division t <- c(8, 3, 4)
%/% of first vector with print(v%/%t)
second (quotient) it produces the following result −
[1] 0 1 1

v <- c( 2,5.5,6)
The first vector raised t <- c(8, 3, 4)
^ to the exponent of print(v^t)
second vector it produces the following result −
[1] 256.000 166.375 1296.000

2. Relational Operator:- Relational operators are used to compare between values.Each element of the
first vector is compared with the corresponding element of the second vector. The result of comparison
is a Boolean value.

Operator Description Example

v <- c(2,5.5,6,9)
Checks if each element of the first vector is t <- c(8,2.5,14,9)
> greater than the corresponding element of the print(v>t)
second vector. it produces the following result −
[1] FALSE TRUE FALSE FALSE

v <- c(2,5.5,6,9)
Checks if each element of the first vector is less t <- c(8,2.5,14,9)
< than the corresponding element of the second print(v < t)
vector. it produces the following result −
[1] TRUE FALSE TRUE FALSE
STATISTICS WITH R PROGRAMMING Unit - 2

v <- c(2,5.5,6,9)
Checks if each element of the first vector is t <- c(8,2.5,14,9)
== equal to the corresponding element of the print(v == t)
second vector. it produces the following result −
[1] FALSE FALSE FALSE TRUE

v <- c(2,5.5,6,9)
Checks if each element of the first vector is less t <- c(8,2.5,14,9)
<= than or equal to the corresponding element of print(v<=t)
the second vector. it produces the following result −
[1] TRUE FALSE TRUE TRUE

v <- c(2,5.5,6,9)
Checks if each element of the first vector is t <- c(8,2.5,14,9)
>= greater than or equal to the corresponding print(v>=t)
element of the second vector. it produces the following result −
[1] FALSE TRUE FALSE TRUE

v <- c(2,5.5,6,9)
t <- c(8,2.5,14,9)
Checks if each element of the first vector is print(v!=t)
!= unequal to the corresponding element of the
second vector. it produces the following result −
[1] TRUE TRUE TRUE FALSE

3) Logical Operators:- It is applicable only to vectors of type logical, numeric or complex. Zero is
considered FALSE and non-zero numbers are taken as TRUE. Each element of the first vector is
compared with the corresponding element of the second vector. The result of comparison is a Boolean
value.
Operator Description Example

It is called Element-wise Logical AND v <- c(3,1,TRUE,2+3i)


operator. It combines each element of the first t <- c(4,1,FALSE,2+3i)
vector with the corresponding element of the print(v&t)
& second vector and gives a output TRUE if both
the elements are TRUE. it produces the following result −
[1] TRUE TRUE FALSE TRUE

v <- c(3,0,TRUE,2+2i)
It is called Element-wise Logical OR operator. t <- c(4,0,FALSE,2+3i)
It combines each element of the first vector print(v|t)
| with the corresponding element of the second
vector and gives a output TRUE if one the it produces the following result −
elements is TRUE. [1] TRUE FALSE TRUE TRUE

v <- c(3,0,TRUE,2+2i)
It is called Logical NOT operator. Takes each print(!v)
! element of the vector and gives the opposite
logical value. it produces the following result −
[1] FALSE TRUE FALSE FALSE
STATISTICS WITH R PROGRAMMING Unit - 2

The logical operator && and || considers only the first element of the vectors and give a vector
of single element as output.
Operator Description Example

v <- c(3,0,TRUE,2+2i)
Called Logical AND operator. Takes t <- c(1,3,TRUE,2+3i)
first element of both the vectors and print(v&&t)
&&
gives the TRUE only if both are
it produces the following result −
TRUE.
[1] TRUE

Called Logical OR operator. Takes v <- c(0,0,TRUE,2+2i)


first element of both the vectors and t <- c(0,3,TRUE,2+3i)
|| print(v||t)
gives the TRUE if one of them is
TRUE. it produces the following result −[1] FALSE

4) Assignment Operators:- These operators are used to assign values to vectors.

Operator Description Example

v1 <- c(3,1,TRUE,2+3i)
v2 <<- c(3,1,TRUE,2+3i)
v3 = c(3,1,TRUE,2+3i)
<− print(v1)
or print(v2)
= Called Left Assignment print(v3)
or it produces the following result −
<<− [1] 3+0i 1+0i 1+0i 2+3i
[1] 3+0i 1+0i 1+0i 2+3i
[1] 3+0i 1+0i 1+0i 2+3i

c(3,1,TRUE,2+3i) -> v1
c(3,1,TRUE,2+3i) ->> v2
-> print(v1)
print(v2)
or Called Right Assignment
->> it produces the following result −
[1] 3+0i 1+0i 1+0i 2+3i
[1] 3+0i 1+0i 1+0i 2+3i

5) Miscellaneous Operators:- These operators are used to for specific purpose and not general
mathematical or logical computation.
Operator Description Example

Colon v <- 2:8


operator. It print(v)
creates the
: series of it produces the following result −
numbers in [1] 2 3 4 5 6 7 8
sequence
for a vector.

This v1 <- 8
operator is v2 <- 12
%in%
used to t <- 1:10
identify if print(v1 %in% t)
STATISTICS WITH R PROGRAMMING Unit - 2

an element print(v2 %in% t)


belongs to a it produces the following result −
vector.
[1] TRUE
[1] FALSE

M = matrix( c(2,6,5,1,10,4), nrow = 2,ncol = 3,byrow =


This TRUE)
operator is t = M %*% t(M)
used to print(t)
%*% multiply a
it produces the following result −
matrix with
its [,1] [,2]
transpose. [1,] 65 82
[2,] 82 117

Functions:- A function is a block or chunck of code having a


specific structure, which is often singular or atomic nature,
and can be reused to accomplish a specific nature. A function
helps to divide a large program into modules to enhance
readability and code reuse. or A function is a group of
instructions that takes inputs, uses them to compute other
values, and returns a result.
structure of a function
function_name <- function(arguments)
{
statements Built-in functions in R
}
 The word ‗function‘ is a keyword which is used to specify the statements enclosed within the
curly braces are part of the function.
 Function_name is used to identify the function
 Function consists of formal arguments and body
 The function is called using the following statement: function_name(arguments)
Example:
say.hello <- function() g <- function(x)
{ {
print("Hello, World!") x<- x+1
} return(x)
say.hello() }
[1] "Hello, World!" g(2)
[1] 3

 Functions are assigned to objects just like any other variable, using <- operator.
 Function are a set of parentheses that can either be empty – not have any arguments – or
contain any number of arguments.
 The body of the function is enclosed in curly braces ({ and }).This is not necessary if the
function contains only one line.
 A semicolon(;) can be used to indicate the end of the line but is not necessary.

# counts the number of odd integers in x


> oddcount <- function(x)
{
k <- 0 # assign 0 to k
for (n in x) {
if (n %% 2 == 1) k <- k+1 # %% is the modulo operator
}
STATISTICS WITH R PROGRAMMING Unit - 2

return(k)
}
> oddcount(c(1,3,5))
[1] 3
> oddcount(c(1,2,3,7,9))
[1] 4

Variables created outside functions are global and are available within functions as well. Example:
> f <- function(x) return(x+y)
> y <- 3
> f(5)
[1] 8
Here y is a global variable. A global variable can be written to from within a function by using R‘s
superassignment operator, <<-.

Default Arguments:- R also makes frequent use of default arguments. Consider a function definition
like this:
> g <- function(x,y=2,z=T) { ... }

Here y will be initialized to 2 if the programmer does not specify y in the call. Similarly, z will have the
default value TRUE. Now consider this call:

> g(12,z=FALSE)
Here, the value 12 is the actual argument for x, and we accept the default value of 2 for y, but we
override the default for z, setting its value to FALSE.

Default Values for Arguments:-


> my_matrix<- matrix (1:12,4,3,byrow= TRUE)
The argument byrow= TRUE tells R that the matrix should be filled in row wise. In this example the
default argument is byrow = FALSE, the matrix is filled in column wise.

Lazy Evaluation of Function:- Arguments to functions are evaluated lazily, which means so they are
evaluated only when needed by the function body.
# Create a function with arguments.
new.function <- function(a, b) {
print(a^2)
print(a)
print(b)
}
# Evaluate the function without supplying one of the arguments.
new.function(6)
When we execute the above code, it produces the following result −
[1] 36
[1] 6
Error in print(b) : argument "b" is missing, with no default

Return Values:- Functions are generally used for computing some value, so they need a mechanism to
supply that value back to the caller.This is called returning.
STATISTICS WITH R PROGRAMMING Unit - 2

 The return value of a function can be any R object. Although the return value is often a list, it
could even be another function.
 You can transmit a value back to the caller by explicitly calling return(). Without this call, the
value of the last executed statement will be returned by default.
 If the last statement in the call function is a for( ) statement, which returns the value NULL.

# First build it without an explicit return # Now build it with an explicit return
num <- function(x) num <- function(x)
{ {
x*2 return(x*2)
} }
> num(5) > num(5)
[1] 10 [1] 10

# build it again, this time with another argument after the explicit return
num <- function(x)
{
return(x*2)
#below here is not executed because the return function already exists.
print("VISHNU")
return(17)
}
> num(5)
[1] 10

# if the last statement is for loop or any empty statement then it return NULL.
num <- function(x)
{ }
> num(5)
[1] NULL

Deciding Whether to Explicitly Call return():-The R idiom is to avoid explicit calls to return(). One of
the reasons cited for this approach is that calling that function lengthens execution time. However,
unless the function is very short, the time saved is negligible, so this might not be the most compelling
reason to refrain from using return(). But it usually isn‘t needed.
#Example to count the odd numbers with no return statement
oddcount <- function(x) {
k <- 0 Both programs
for (n in x) { results in same
if (n %% 2 == 1) k <- k+1 output with and
}
k without return
}
> oddcount(c(12,2,5,9,7))
[1] 3

#Example to count the odd numbers with return statement


oddcount <- function(x) {
k <- 0
for (n in x) {
if (n %% 2 == 1) k <- k+1
}
return(k)
}
> oddcount(c(12,2,5,9,7))
[1] 3
STATISTICS WITH R PROGRAMMING Unit - 2

Good software design, can glance through a function‘s code and immediately spot the various
points at which control is returned to the caller. The easiest way to accomplish this is to use an
explicit return() call in all lines in the middle of the code that cause a return.

Returning Complex Objects:- The return value can be any R object, you can return complex objects.
Here is an example of a function being returned:
g<-function() {
x<- 3
t <- function(x) return(x^2)
return(t)
}

> g()
function(x) return(x^2)
<environment: 0x16779d58>
If your function has multiple return values, place them in a list or other container.

Functions are Objective:- R functions are first-class objects (of the class "function"), meaning that they
can be used for the most part just like other objects. This is seen in the syntax of function creation:
g <- function(x)
{
return(x+1)
}
function( ) is a built-in R function whose job is to create functions.On the right-hand side, there are really
two arguments to function(): The first is the formal argument list for the function i.e, x and the second is
the body of that function return(x+1). That second argument must be of class "expression". So, the point
is that the right-hand side creates a function object, which is then assigned to g.
> ?"{" Its job is the make a single unit of what could be several statements.
 formals( ) :- Get or set the formal arguments of a function
> formals(g) # g is a function with formal arguments ―x‖
$x
 body( ) :- Get or set the body of a function
> body(g) # g is a function
{
x <- x + 1
return(x)
}
 Replacing body of the function: quote( ) is used to substitute expression
> g <- function(x) return(x+1)
> body(g) <- quote(2*x+3)
>g
function (x)
2*x+3
 Typing the name of an object results in printing that object to the screen which is similar to
all objects
>g
function(x)
{
return(x+1)
}
 Printing out a function is also useful if you are not quite sure what an R library function
does. Code of a function is displayed by typing the built-in function name.
> sd
function (x, na.rm = FALSE)
sqrt(var(if (is.vector(x) || is.factor(x)) x else as.double(x),
na.rm = na.rm))
<bytecode: 0x17b49740> <environment: namespace:stats>
STATISTICS WITH R PROGRAMMING Unit - 2

 Some of R‘s most fundamental built-in functions are written directly in C, and thus they
are not viewable in this manner.
> sum
function (..., na.rm = FALSE) .Primitive("sum")
 Since functions are objects, you can also assign them, use them as arguments to other
functions, and so on.
> f1 <- function(a,b) return(a+b)
> f2 <- function(a,b) return(a-b)
> f <- f1 # Assigning function object to other object
> f(3,2)
[1] 5
> g <- function(h,a,b) h(a,b) # passing function object as an arguments
> g(f1,3,2)
[1] 5
> g(f2,3,2)
[1] 1

No Pointers in R:- R does not have variables corresponding to pointers or references like C language.
This can make programming more difficult in some cases.
The fundamental thought is to create a class constructor and have every instantiation of the
class be its own environment. One can then pass the object/condition into a function and it will be
passed by reference instead of by value, because unlike other R objects, environments are not copied
when passed to functions. Changes to the object in the function will change the object in the calling
frame. In this way, one can operate on the object and change internal elements without having to create
a copy of the object when the function is called, nor pass the entire object back from the function. For
large objects, this saves memory and time.
For example, you cannot write a function that directly changes its arguments.

> x <- c(12,45,6)


> sort(x)
[1] 6 12 45
>x
[1] 12 45 6
The argument to sort() does not change. If we do want x to change in this R code, the solution is to
reassign the arguments:
> x <- sort(x)
>x
[1] 6 12 45

If a function has several output then a solution is to gather them together into a list, call the function
with this list as an argument, have the function return the list, and then reassign to the original list.
An example is the following function, which determines the indices of odd and even numbers in a
vector of integers:
> y <-function(v){
odds <- which(v %% 2 == 1)
evens <- which(v %% 2 == 0)
list(o=odds,e=evens)
}
> y(c(2,34,1,5))
$o
[1] 3 4

$e
[1] 1 2

Recursion:- Recursion is a programming technique in which, a function calls itself repeatedly for some
input.
STATISTICS WITH R PROGRAMMING Unit - 2

To solve a problem of type X by writing a recursive function f():


1. Break the original problem of type X into one or more smaller
problems of type X.
2. Within f(), call f() on each of the smaller problems.
3. Within f(), piece together the results of (b) to solve the original
problem.
# Recursive function to find factorial
recursive.factorial <- function(x)
{
if (x == 0) return (1)
else return (x * recursive.factorial(x-1))
}
> recursive.factorial(5)
[1] 120

r = fact(4)
24
return(4*(fact(3))
6
return(3*(fact(2))
2
return(2*(fact(1))
1
return(1)

A Quicksort Implementation:- Quick sort is also known as Partition-Exchange sort and is based on
Divide and conquer Algorithm design method. This was proposed by C.A.R Hoare. The basic idea of
quick sort is very simple. We consider one element at a time (pivot element). We have to move the pivot
element to the final position that it should occupy in the final sorted list. While identifying this position,
we arrange the elements, such that the elements to the left of the pivot element will be less than pivot
element & elements to the right of the pivot element will be greater than pivot element. There by
dividing the list by 2 parts. We have to apply quick sort on these 2 parts recursively until the entire list is
sorted.

For instance, suppose we wish to sort the vector (5,4,12,13,3,8,88). We first compare everything to the
first element, 5, to form two subvectors: one consisting of the elements less than 5 and the other
consisting of the elements greater than or equal to 5. That gives us subvectors (4,3) and (12,13,8,88). We
then call the function on the subvectors, returning (3,4) and (8,12,13,88). We string those together with
the 5, yielding (3,4,5,8,12,13,88), as desired. R‘s vector-filtering capability and its c() function make
implementation of Quicksort quite easy.

# Quicksort recursive function


qs <- function(x) {
if (length(x) <= 1) return(x)
pivot <- x[1]
therest <- x[-1]
sv1 <- therest[therest < pivot]
sv2 <- therest[therest >= pivot] > qs(c(12,6,7,34,3))
sv1 <- qs(sv1) [1] 3 6 7 12 34
sv2 <- qs(sv2)
return(c(sv1,pivot,sv2)) }
STATISTICS WITH R PROGRAMMING Unit - 2

Binary search tree:- The nature of binary search trees implies that at any node, all of the elements in
the node‘s left subtree are less than or equal to the value stored in this node, while the right subtree
stores the elements that are larger than the value in this mode. In our example tree, where the root
node contains 8, all of the values in the left subtree-5, 2 and 6-are less than 8, while 20 is greater than 8.

The code follows. Note that it includes only routines to insert new items and to traverse the tree.
# storage is in a matrix, say m, one row per node of the tree; a link i in the tree means the vector
#m[i,] = (u,v,w); u and v are the left and right links, and w is the stored value; null links have the value
#NA; the matrix is referred to as the list (m,nxt,inc), where m is the matrix, nxt is the next empty row to
#be used, and inc is the number of rows of expansion to be allocated when the matrix becomes full

# initializes a storage matrix, with initial stored value firstval


newtree <- function(firstval,inc) {
m <- matrix(rep(NA,inc*3),nrow=inc,ncol=3)
m[1,3] <- firstval
return(list(mat=m,nxt=2,inc=inc))
}

# inserts newval into nonempty tree whose head is index hdidx in the storage space treeloc; note that
#return value must be reassigned to tree; inc is as in newtree() above
ins <- function(hdidx,tree,newval,inc) {
tr <- tree
# check for room to add a new element
tr$nxt <- tr$nxt + 1
if (tr$nxt > nrow(tr$mat))
tr$mat <- rbind(tr$mat,matrix(rep(NA,inc*3),nrow=inc,ncol=3))
newidx <- tr$nxt # where we'll put the new tree node
tr$mat[newidx,3] <- newval
idx <- hdidx # marks our current place in the tree
node <- tr$mat[idx,]
nodeval <- node[3]
while (TRUE) {
# which direction to descend, left or right?
if (newval <= nodeval) dir <- 1 else dir <- 2
# descend
# null link?
if (is.na(node[dir])) {
tr$mat[idx,dir] <- newidx
break
} else {
idx <- node[dir]
node <- tr$mat[idx,]
nodeval <- node[3]
}
}
return(tr)
}
STATISTICS WITH R PROGRAMMING Unit - 2

# print sorted tree via inorder traversal


printtree <- function(hdidx,tree) {
left <- tree$mat[hdidx,1]
if (!is.na(left)) printtree(left,tree)
print(tree$mat[hdidx,3])
right <- tree$mat[hdidx,2]
if (!is.na(right)) printtree(right,tree)
}

sapply( ):- sapply is wrapper class to lapply with difference being it returns vector or matrix instead of
list object.
Syntax: sapply(X, FUN, ...,)
# create a list with 2 elements
x = (a=1:10,b=11:20) # mean of values using sapply
sapply(x, mean)
a b
5.5 15.5

tapply( ):- tapply() applies a function or operation on subset of the vector broken down by a given factor
variable.
To understand this, imagine we have ages of 20 people (male/females), and we need to know the
average age of males and females from this sample. To start with we can group ages by the gender
(male or female), ages of 12 males, and ages of 8 females, and later calculate the average age for
males and females.
Syntax of tapply: tapply(X, INDEX, FUN, …)
X = a vector, INDEX = list of one or more factor, FUN = Function or operation that needs to be
applied, … optional arguments for the function
> ages <- c(25,26,55,37,21,42)
> affils <- c("R","D","D","R","U","D")
> tapply(ages,affils,mean)
DRU
41 31 21
STATISTICS WITH R PROGRAMMING Unit - 3

Doing Math and Simulation in R:- Math Function, Extended Example Calculating Probability- Cumulative
Sums and Products-Minima and Maxima- Calculus, Functions Fir Statistical Distribution, Sorting, Linear
Algebra Operation on Vectors and Matrices, Extended Example: Vector cross Product- Extended Example:
Finding Stationary Distribution of Markov Chains, Set Operation, Input /out put, Accessing the Keyboard and
Monitor, Reading and writer Files

Math Function : R contains built-in functions for various math operations and for
statistical distributions.

Function Explanation Example


exp( ) Exponential function, base e > exp(2)
[1] 7.389056
log( ) Natural logarithm > log(10)
[1] 2.302585
log10( ) Logarithm base 10 > log10(10)
[1] 1
sqrt( ) Square root > sqrt(16)
[1] 4
abs( ) Absoluate value > abs(-12.4)
[1] 12.4
sin( ) Trig functions > sin(40)
[1] 0.7451132
cos( ) Trig functions > cos(12)
[1] 0.843854
min( ) Minimum value within a vector > x <- c(1,4,-423,8,-2,23)
> min(x)
[1] -423
max( ) Maximum value within a vector > x <- c(1,4,-423,8,-2,23)
> max(x)
[1] 23
which.min( ) Index of minimal element of the vector > x <- c(1,4,-423,8,-2,23)
> which.min(x)
[1] 3
which.max( ) Index of maximal element of the vector > x <- c(1,4,-423,8,-2,23)
> which.max(x)
[1] 6
pmin( ) Element-wise minima of several vectors > x <- c(4,-5,56)
> y <- c(3,2,7)
> pmin(x,y)
[1] 3 -5 7
pmax( ) Element-wise maxima of several vectors > x <- c(4,-5,56)
> y <- c(3,2,7)
> pmax(x,y)
[1] 4 2 56
sum( ) Sum of the elements of the vector >x
[1] 4 -5 56
> sum(x)
[1] 55
prod( ) Product of the elements of the vector > y <- 1:3
> prod(y)
[1] 6
cumsum( ) Cumulative sum of the elements of a >y
vector [1] 1 2 3
> cumsum(y)
STATISTICS WITH R PROGRAMMING Unit - 3

[1] 1 3 6
cumprod( ) Cumulative product of the elements of a > z <- c(2,5,3)
vector > cumprod(z)
[1] 2 10 30
round( ) Round of the closest integer > round(12.4)
[1] 12
> round(2.43,digits=1)
[1] 2.4
floor( ) Round of the closest integer below > floor(12.4)
[1] 12
ceiling( ) Round of the closest integer above > ceiling(12.4)
[1] 13
factorial( ) Factorial function > factorial(5)
[1] 120
sin(), cos(), tan() and so on: Trig functions, the arguments will be in radians,asin(), acos(), atan() inverse
trignometry functions.
> tan(45*pi/180)
[1] 1
> a<-tan(45*pi/180)
> b<-atan(a)
>b
[1] 0.7853982
> b*180/pi
[1] 45
sum(): sum returns the sum of all the values present in its arguments.
sum(..., na.rm = FALSE)
... : numeric or complex or logical vectors.
na.rm : logical. Should missing values (including NaN) be removed?
Example1:- Example2:-
>x y <- c(2,3,NA,1)
[1] 4 -5 56 >sum(y)
> sum(x) [1] NA
[1] 55 >sum(y, na.rm=TRUE)
[1] 6
prod(): prod returns the product of all the values present in its arguments.
prod(..., na.rm = FALSE)
... : numeric or complex or logical vectors.
na.rm : logical. Should missing values (including NaN) be removed?
Example1:- Example 2:-
> x <- c(1,3,5) >y
>prod(x) [1] 2 3 NA 1
[1] 15 >prod(y)
[1] NA
> prod(y, na.rm=TRUE)
[1] 6

Extended Example: Calculating a probability :


Now we see how to find the probability that exactly one event occur: If three friends x, y, z appeared for an
examination x has17% chance of failure, y has 7% chance of failure, and Z has 26% chance of failure.
What is the probability that exactly one of them will fail in the exams?
P(X fails, but not others) = 0.17 * 0.93 * 0.74,
P(Y fails, but not others) = 0.83 * 0.07 * 0.74,
P(Z fails, but not others) = 0.83 * 0. 93 * 0.26.

The probability can be calculated using the prod() function. Let us assume that there are ‗n‘ independent
events with the ith event having the pi probability of occurrence.
What is the probability of exactly one of these events occurring?
STATISTICS WITH R PROGRAMMING Unit - 3

Considering an example where the value of n is 3. The events are named A, B, and C. Then we
break down the computation as follows:
P(exactly one event occurs) = P(A and not B and not C) +
P(not A and B and not C) +
P(not A and not B and C)
P(A and not B and not C) would be pA (1 − pB) (1 − pC), and so on.
For general n, that is calculated as follows
n

 p (1  p )....(1  p
i1
i 1 i1 )(1  pi1 ).... (1  pn )
(The ith term inside the sum is the probability that event i occurs and all the others do not occur.)
Here‘s code to compute this, with our probabilities pi contained in the vector p:
exactlyone <- function(p) {
notp <- 1 - p
tot <- 0.0
for (i in 1:length(p))
tot <- tot + p[i] * prod(notp[-i])
return(tot)
}
notp <- 1 – p :- creates a vector of all the ―not occur‖ probabilities 1 − pj , using recycling.
The expression notp[-i] computes the product of all the elements of notp, except the ith

Cumulative Sums and Products:-


A cumulative product is a sequence of partial products of a given sequence. For example, the
cumulative products of the sequence {a,b,c,.....} are a,ab,abc , ....... Returns a vector whose elements are the
cumulative product.
> x <- c(2,4,3)
> cumprod(x)
[1] 2 8 24
A cumulative sum is a sequence of partial sum of a given sequence. For example, the
cumulative sum of the sequence {a,b,c,.....} are a,ab,abc , .... Returns a vector whose elements are the
cumulative sum.
> x <- c(2,4,3)
> cumprod(x)
[1] 2 6 9

Minima and maxima:-


max() function computes the maximun value of a vector.
min() function computes the minimum value of a vector.
• x: number vector
• na.rm: whether NA should be removed, if not, NA will be returned
 max(..., na.rm = FALSE)
> max(c(12,4,6,NA,34))
[1] NA
> max(c(12,4,6,NA,34),na.rm=FALSE)
[1] NA
> max(c(12,4,6,NA,34),na.rm=TRUE)
[1] 34
> x <- c(2,-4,6,-34)
> min(x[1],x[4])
[1] -34

 min(..., na.rm = FALSE)


> min(c(12,4,6,NA,34))
[1] NA
> min(c(12,4,6,NA,34),na.rm=TRUE)
STATISTICS WITH R PROGRAMMING Unit - 3

[1] 4
> min(c(12,4,6,NA,34),na.rm=FALSE)
[1] NA
> x <- c(2,-4,6,-34)
> max(x[2],x[3])
[1] 6

which.min() and which.max(): Index of the minimal element and maximal element of a vector.
>x <- c(1,4,-423,8,-2,23)
> which.min(x)
[1] 3
> which.max(x)
[1] 6

pmin() and pmax(): Element-wise minima and maxima of several vectors.


There is quite a difference between min() and pmin(). The former simply combines all its arguments into
one long vector and returns the minimum value in that vector. In contrast, if pmin() is applied to two or
more vectors, it returns a vector of the pair-wise minima, hence the name pmin.
The max() and pmax() functions act analogously to min() and pmin().
 pmax(..., na.rm = FALSE)
> x <- c(12,4,6,NA) pmin and pmax are the
> y <- c(2,34,56,1) ‘parallel’ versions of the
> pmax(x,y) min and max function,
[1] 12 34 56 NA meaning that they can take
> pmax(x,y,na.rm=TRUE) vector arguments and
[1] 12 34 56 1 return vectors back.
 pmin(..., na.rm = FALSE)
>x
[1] 12 4 NA 3
>y
[1] 1 2 3 4
> pmin(x,y)
[1] 1 2 NA 3
> pmin(x,y,na.rm=TRUE)
[1] 1 2 3 3

Function minimization/maximization can be done via nlm() and optim(). For example, let‘s find the
smallest value of f(x) = x2 − sin(x).
> nlm(function(x) return(x^2-sin(x)),8)
$minimum
[1] -0.2324656
$estimate
[1] 0.4501831
$gradient
[1] 4.024558e-09
$code
[1] 1
$iterations
[1] 5

Here, the minimum value was found to be approximately −0.23, occurring at x = 0.45. A Newton-
Raphson method (a technique from numerical analysis for approximating roots) is used, running five
iterations in this case. The second argument specifies the initial guess, which we set to be 8.

Calculus:- R also has some calculus capabilities, including symbolic differentiation and numerical
integration.
> D(expression(exp(x^2)),"x") # derivative
exp(x^2) * (2 * x)
STATISTICS WITH R PROGRAMMING Unit - 3

> integrate(function(x) x^2,0,1)


0.3333333 with absolute error < 3.7e-15
1
d x2
e  2xex and x2dx  0.33333333
2
Here, R reported
dx 0
R packages for differential equations , for interfacing R with the Yacas symbolic math system
(ryacas), and for other calculus operations. These packages, and thousands of others, are available
from the Comprehensive R Archive Network (CRAN)

Functions Fir Statistical Distribution:- R has functions available for most of the famous statistical
distributions.
Prefix the name as follows:
• With d for the density or probability mass function (pmf)
• With p for the cumulative distribution function (cdf)
• With q for quantiles
• With r for random number generation
The rest of the name indicates the distribution. Table 8-1 lists some common statistical distribution
functions.
Distribution Density/pmf cdf Quantiles Random numbers
Normal dnorm() pnorm() qnorm() rnorm()
Chi square dchisq() pchisq() qchisq() rchisq()
Binomial dbinom() pbinom() qbinom() rbinom()

As an example, simulate 1,000 chi-square variates with 2 degrees of freedom and find their mean.
> mean(rchisq(1000,df=2))
[1] 1.938179
The r in rchisq specifies that we wish to generate random numbers— in this case, from the chi-square
distribution. As seen in this example, the first argument in the r-series functions is the number of random
variates to generate.
These functions also have arguments specific to the given distribution families. In our example, we
use the df argument for the chi-square family, indicating the number of degrees of freedom.
Let‘s also compute the 95th percentile of the chi-square distribution with two degrees of freedom:
> qchisq(0.95,2)
[1] 5.991465
Here, we used q to indicate quantile—in this case, the 0.95 quantile, or the 95th percentile. The first
argument in the d, p, and q series is actually a vector so that we can evaluate the density/pmf, cdf, or
quantile function at multiple points. Let‘s find both the 50th and 95th percentiles of the chi-square
distribution with 2 degrees of freedom.
qchisq(c(0.5,0.95),df=2)
[1] 1.386294 5.991465

Sorting:- Sorting is nothing but storage of data in sorted order, it can be in ascending or descending order.
> x <- c(12,4,25,4)
> sort(x)
[1] 4 4 12 25
>x
[1] 12 4 25 4
The vector x did not change actually as printed in the very last line of the code. In order to sort the indexes
as such, the order function is used in the following manner.
> order(x)
[1] 2 4 1 3
The console represents that there are two smallest values in vector x. The third smallest value being x[1],
and so on. The same function order can also be used along with indexing for sorting data frames. This
function can also be used to sort the characters as well as numeric values.
Another function which specifies the rank of every single element present in a vector is called rank( )
STATISTICS WITH R PROGRAMMING Unit - 3

>x
[1] 12 4 25 4
> rank(x)
[1] 3.0 1.5 4.0 1.5
The above console demonstrates that the value 12 lies at rank 4th, which means that the 3rd smallest element
in x is 12. Now, 4 number appears two times in the vector x. So, the rank 1.5 is allocated to both the
numbers.
Example:- using order function on a dataframe.
> age <- c(12,4,34,14)
> names <- c("A","B","C","D")
> df <- data.frame(age,names)
> df
age names
1 12 A
2 4 B
3 34 C
4 14 D
> df[order(df$age),]
age names
2 4 B
1 12 A
4 14 D
3 34 C

Linear Algebra Operation on Vectors and Matrices:- The vector quantity can be multiplied to a scalar
quantity as demonstrated:
> x <- c(13,5,12,5)
> y <-2*x
>y
[1] 26 10 24 10
To compute the inner product (or dot product) of two vectors, use crossprod(),
> a<-c(3,7,2)
> b<-c(2,5,8)
> crossprod(a,b)
[,1]
[1,] 57
The function computed 3·2+7·5+ 2·8 = 57.
Note that the name crossprod() is a misnomer, as the function does not compute the vector cross product.

For matrix multiplications, the operator to use is %*% not *.


> c<-matrix(1:4,ncol=2)
>c
[,1] [,2]
[1,] 1 3
[2,] 2 4
> d<-matrix(rep(1,4),ncol=2)
>d
[,1] [,2]
[1,] 1 1
[2,] 1 1
> c%*%d
[,1] [,2]
[1,] 4 4
[2,] 6 6

The function solve() will solve systems of linear equations and even find matrix inverses. For example, let‘s
solve this system:
x1 + x2 =2
STATISTICS WITH R PROGRAMMING Unit - 3

−x1 + x2 =4
 1 1 x1   2
1  x    4 
 1 2   
> a<-matrix(c(1,1,-1,1),ncol=2,byrow=T)
> b<-c(2,4)
> solve(a,b)
[1] -1 3
> solve(a)
[,1] [,2]
[1,] 0.5 -0.5
[2,] 0.5 0.5
In the second call solve(), we are not giving second argument so it computers inverse of the matrix.
Few other linear algebra functions are,
 t(): Matrix transpose
 qr(): QR decomposition
 chol(): Cholesky decomposition
 det(): Determinant
 eigen(): Eigen values/eigen vectors
 diag(): Extracts the diagonal of a square matrix (useful for obtaining variances from a covariance
matrix and for constructing a diagonal matrix).
 sweep(): Numerical analysis sweep operations

Note the versatile nature of diag(): If its argument is a matrix, it returns a vector, and vice versa. Also, if the
argument is a scalar, the function returns the identity matrix of the specified size.
> x<-matrix(1:9,ncol=3)
> diag(x)
[1] 1 5 9
> a<-c(1,2,3)
> diag(a)
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 0 2 0
[3,] 0 0 3
> diag(3)
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 0 1 0
[3,] 0 0 1
The sweep() function is capable of fairly complex operations. As a simple example, let‘s take a 3-by-3
matrix and add 1 to row 1, 4 to row 2, and 7 to row 3.
>a
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
> sweep(a,1,c(3,4,5),"+")
[,1] [,2] [,3]
[1,] 4 7 10
[2,] 6 9 12
[3,] 8 11 14
> sweep(a,2,c(3,4,5),"+")
[,1] [,2] [,3]
[1,] 4 8 12
[2,] 5 9 13
[3,] 6 10 14
STATISTICS WITH R PROGRAMMING Unit - 3

The first two arguments to sweep() are like those of apply(): the array and the margin, which is 1 for rows
in this case. The fourth argument is a function to be applied, and the third is an argument to that function.

Vector Cross Product:- Let‘s consider the issue of vector cross products. The definition is very simple:
The cross product of vectors (x 1, x2, x3) and (y1, y2, y3) in three dimensional space is a new three-
dimensional vector, as (x2y3 − x3y2, −x1y3 + x3y1, x1y2 − x2y1)
This can be expressed compactly as the expansion along the top row of the determinant, Here, the
elements in the top row are merely placeholders.
   
 
 x1 x2 x3 

y y y 
 1 2 3 

The point is that the cross product vector can be computed as a sum of subdeterminants. For
instance, the first component in Equation 8.1, x2y3 − x3y2, is easily seen to be the determinant of
the submatrix obtained by deleting the first row and first column.
 x2 x 
 3

 y2 y3 
Function to calculate cross product of vectors:
xprod <- function(x,y)
{
m <- rbind(rep(NA,3),x,y)
xp <- vector(length=3)
for (i in 1:3)
xp[i] <- -(-1)^i * det(m[2:3,-i])
return(xp)
}
> xprod(c(12,4,2),c(2,1,1))
[1] 2 -8 4

Set Operations:- R includes some handy set operations, including these:


1) union(x,y): The union of two sets is defined as the set of all the elements
that are members of set A, set B or both and is denoted by A  B read as
A union B.
A B {x | x A or xB}

Eg: A = {1,2,3,4,5,a,b} B = {a,b,c,d,e}


A  B = {1,2,3,4,5,a,b}  {a,b,c,d,e}
= {1,2,3,4,5,a,b,c,d,e}

2) intersect(x,y): The intersection of any two sets A and B is the set


containing of all the elements that belong to both A and B is denoted
by A  B read as A intersection B.
A  B {x | x A and x  B}

Eg: A = {1,2,3,4,5,a,b} B = {a,b,c,d,e}


A  B = {1,2,3,4,5,a,b}  {a,b,c,d,e}
= {a,b}
STATISTICS WITH R PROGRAMMING Unit - 3

3) setdiff(x,y): The set difference of any two sets A and B is the set of
elements that belongs to A but not B. It is denoted by A-B and read as
‗A difference B‘. A-B is also denoted by A|B or A~B. It is also called
the relative complement of B in A.
Eg: A = {1,2,3,4,5,6} B = {3,5,7,9}
A-B = {1,2,4,6}
B-A = {7,9}

4) setequal(x,y): Test for equality between x and y. If both x and y are equal it returns TRUE
otherwise returns FALSE
5) c %in% y: Membership, testing whether c is an element of the set y. It checks every
corresponding element of ‗c‘ with ‗y‘,if both elements are equal it returns TRUE else return FALSE.
6) choose(n,r): Number of possible subsets of size k chosen from a set of size n
Eg:- > choose(2,1)
[1] 2
choose() function computes the combination nCr.
n: n elements
r: r subset elements
...
nCr = n!/(r! * (n-r)!)

> x <- c(1,5,3) > setequal(x,y)


> y <- c(34,2,5) [1] FALSE
> union(x,y) >choose(5,2)
[1] 1 5 3 34 2 [1] 10
>intersect(x,y) >x %in% y
[1] 5 [1] FALSE TRUE FALSE
> setdiff(x,y) > 5 %in% y
[1] 1 3 [1] TRUE

? Code the symmetric difference between two sets— that is, all the elements belonging to exactly one of
the two operand sets. Because the symmetric difference between sets x and y consists exactly of those
elements in x but not y and vice versa.
function(a,b) >x
{ [1] 1 2 5
sdfxy <- setdiff(x,y) >y
sdfyx <- setdiff(y,x) [1] 5 1 8 9
return(union(sdfxy,sdfyx)) > symdiff(x,y)
} [1] 2 8 9

? Write a binary operand for determining whether one set u is a subset of another set v.
Hint: A bit of thought shows that this property is equivalent to the intersection of u and v being equal
to u.
"%subsetof%" <- function(u,v)
{
return(setequal(intersect(u,v),u))
}
> c(2,8) %subsetof% 1:10
[1] TRUE
> c(12,8) %subsetof% 1:10
[1] FALSE

combn() :-The function combn() generates combinations. Let‘s find the subsets of {1,2,3} of size 2.
> x <- combn(1:3,2)

>x
STATISTICS WITH R PROGRAMMING Unit - 3

[,1] [,2] [,3]


[1,] 1 1 2
[2,] 2 3 3
> class(x)
[1] "matrix―
The results are in the columns of the output. We see that the subsets of {1,2,3} of size 2 are (1,2),
(1,3), and (2,3).

Input /output:- I/O plays a central role in most real-world applications of computers. Just consider an
ATM cash machine, which uses multiple I/O operations for both input—reading your card and reading
your typed-in cash request—and output—printing instructions on the screen, printing your receipt, and
most important, controlling the machine to output your money!
R is not the tool you would choose for running an ATM, but it features a highly versatile
array of I/O capabilities.

1. Accessing the keyboard and monitor:- R provides several functions for accesssing the keyboard and
monitor. Few of them are scan(), readline(), print(), and cat() functions.

Using the scan( ) Function:-You can use scan() to read in a vector or a list, from a file or the keyboard.
Suppose we have files named z1.txt, z2.txt.
z1.txt contains the following
123
45
6
z2.txt contains the follwing
abc
de f
g
> scan("z1.txt")
Read 4 items
[1] 123 4 5 6
> scan("z2.txt")
Error in scan("z2.txt") : scan() expected 'a real', got 'abc‘
> scan("z2.txt",what="")
Read 4 items
[1] "abc" "de" "f" "g"

The scan() function has an optional argument named what, which specifies mode, defaulting to
double mode. So, the non-numeric contents of the file z2 produced an error. But we then tried again,
with what="". This assigns a character string to what, indicating that we want character mode.

By default, scan() assumes that the items of the vector are separated by whitespace, which includes
blanks, carriage return/line feeds, and horizontal tabs. You can use the optional sep argument for
other situations.

You can use scan() to read from the keyboard by specifying an empty string for the filename:
> scan("")
1: 43 23 65 12
5:
Read 4 items
[1] 43 23 65 12
> scan("",what="")
1: ―x" ―y" ―z" "srikanth" "Preethi" ―omer"
7:
Read 6 items
[1] ―x" ―y" ―z" "srikanth" "Preethi" ―omer"
STATISTICS WITH R PROGRAMMING Unit - 3

readline() function:- If you want to read in a single line from the keyboard, readline() is very handy.
readline() is called with its optional prompt.
> readline()
Hai how are u
[1] "Hai how are u―
> readline("Enter your Name")
Enter your Name VIT
[1] ―VIT"

Printing to the Screen:- At the top level of interactive mode, you can print the value of a variable or
expression by simply typing the variable name or expression. This won‘t work if you need to print
from within the body of a function. In that case, you can use the print() function,
> x <- 1:3
> print(x^2)
[1] 1 4 9
print() is a generic function, so the actual function called will depend on the class of the object that is
printed. If, for example, the argument is of class "table", then the print.table() function will be called.

It‘s a little better to use cat() instead of print(), as the latter can print only one expression and its
output is numbered, which may be a nuisance. Compare the results of the functions:
> print("abc")
[1] "abc"
> cat("abc\ndef")
abc
def
Note that we needed to supply our own end-of-line character, "\n", in the call to cat(). Without it, our
next call would continue to write to the same line. The arguments to cat() will be printed out with
intervening spaces:
>x
[1] 1 2 3
> cat(x,"abc","de\n")
1 2 3 abc de
If you don‘t want the spaces, set sep to the empty string "", as follows:
> cat(x,"abc","de\n",sep="")
123abcde
Any string can be used for sep. Here, we use the newline character:
>cat(x,"abc","de\n",sep="\n")
1
2
3
abc
de
Set sep can be used with a vector of strings, like this:
> x <- c(5,12,13,8,88)
> cat(x,sep=c(".",".",".","\n","\n"))
5.12.13.8
88

2. Reading and Writing Files:- It includes reading data frames or matrices from files, working with text
files, accessing files on remote machines, and getting file and directory information.

Reading a Data Frame or Matrix from a File:- read.table() is used to read a data frame from the file.
> read.table("z1.txt",header=TRUE)
name nature
1 Hemant Obidient
2 Sowjanya Hardworking
STATISTICS WITH R PROGRAMMING Unit - 3

3 Girija Friendly
4 Preethi Calm
scan() would not work here, as our data-frame has mixture of character and numeric data.We can
read a matrix using scan as
Mat<-matrix(scan(“abc.txt”), nrow=2, ncol=2, byrow=T)
We can do this generally by using read.table() as
read.matrix<-function(filename){
as.matrix(read.table(filename))
}

Reading a Text-File: readLines() is used to read in a text file, either one line at a time or in a single
operation. For example, suppose we have a file z1 with the following contents:
John 25
Mary 28
Jim 19
We can read the file all at once, like this:
>z1 <- readLines("z1")
>z1
[1] "John 25" "Mary 28" "Jim 19"
Since each line is treated as a string, the return value here is a vector of strings—that is, a vector of
character mode.
There is one vector element for each line read, thus three elements here. Alternatively,
we can read it in one line at a time. For this, we first need to create a connection, as described next.

Introduction to Connections: Connection is R‘s term for a fundamental mechanism used in various
kinds of I/O operations. The connection is created by calling file(), url(), or one of several other R
functions. ?connection
> c <- file("z1","r")
> readLines(c,n=1)
[1] "John 25"
> readLines(c,n=1)
[1] "Mary 28"
> readLines(c,n=1)
[1] "Jim 19"
> readLines(c,n=1)
character(0)

We opened the connection, assigned the result to c, and then read the file one line at a time, as
specified by the argument n=1. When R encountered the end of file (EOF), it returned an empty
result.We needed to set up a connection so that R could keep track of our position in the file as we
read through it.
c <- file("z","r")
while(TRUE)
{ OUTPUT:
rl <- readLines(c,n=1) [1] "John 25"
if (length(rl) == 0) [1] "Mary 28"
{ [1] "Jim 19"
print("reached the end") [1] "reached the end"
break
} else print(rl)
}

Accessing files on remote machines via urls: Certain I/O functions, such as read.table() and scan(),
accept web URLs as arguments.
uci <- "http://archive.ics.uci.edu/ml/machine-learning-databases/echocardiogram/ echocardiogram. data”
> ecc <- read.csv(uci)
STATISTICS WITH R PROGRAMMING Unit - 3

Writing to a file:The function write.table() works very much like read.table(), except that it writes a
data frame instead of reading one.
> kids <- c("Jack","Jill")
> ages <- c(12,10)
> d <- data.frame(kids,ages,stringsAsFactors=FALSE)
>d kids ages
1 Jack 12
2 Jill 10
> write.table(d,"kds.txt")

In the case of writing a matrix to a file, just state that you do not want row or column names, as
follows:
write.table(xc, "xcnew", row.names=FALSE, col.names=FALSE)
The function cat() can also be used to write to a file, one part at a time.
> cat("abc\n",file="u")
> cat("de\n",file="u",append=TRUE)

The first call to cat() creates the file u, consisting of one line with contents "abc". The second call
appends a second line. The file is automatically saved after each operation.
writeLines() function can also be used, the counterpart of readLines(). If you use a connection, you
must specify "w" to indicate you are writing to the file, not reading from it:
> c <- file("www","w")
> writeLines(c("abc","de","f"),c)
> close(c)
The file www will be created with these contents:
abc
de
f
STATISTICS WITH R PROGRAMMING

UNIT-IV: Probability Distributions, Normal Distribution- Binomial Distribution- Poisson


Distributions, Other Distribution, Basic Statistics, Correlation and Covariance, T-Tests, ANOVA.

BINOMIAL DISTRIBUTION:- The binomial distribution is a discrete probability distribution. It


describes the outcome of n independent trials in an experiment. Each trial is assumed to have only two
outcomes, either success or failure. If the probability of a successful trial is p, then the probability of
having x successful outcomes in an experiment of n independent trials is as follows.

R has four in-built functions to generate binomial distribution. They are


described below.
 dbinom(x, size, prob) :- This function gives the probability density distribution at each point.
 pbinom(x, size, prob) :- This function gives the cumulative probability of an event. It is a single
value representing the probability.
 qbinom(p, size, prob) :- This function takes the probability value and gives a number whose
cumulative value matches the probability value.
 rbinom(n, size, prob) :- This function generates required number of random values of given
probability from a given sample.
Following is the description of the parameters used −
 x is a vector of numbers.
 p is a vector of probabilities.
 n is number of observations.
 size is the number of trials.
 prob is the probability of success of each trial.
Examples:
 rbinom(n=1,size=10,prob=0.4) - It generates 1 random number from the binomial
distribution basesd on number of successes of 10 independent trails.
 rbinom(n=5,size=10,prob=0.4) - It generates 5 random number from the binomial distribution
basesd on number of successes of 10 independent trails with probability 0.4.
 rbinom(n=5,size=1,prob=0.4) – Setting size to 1 turns the numbers into a bernoulli random
variable, which can take only value 1 (success) or 0 (failure).
 To visualize the binomial distribution we randomly generate 10,000
experiments, each with 10 trails and 0.3 probability.
b <- data.frame(success=rbinom(n=10000,size=10,prob=0.3))
ggplot(b,aes(x=success))+geom_bar()

Problem: Suppose a die is tossed 5 times. What is the probability of getting exactly 2 fours?
Solution: This is a binomial experiment in which the number of trials is equal to 5, the number of
successes is equal to 2, and the probability of success on a single trial is 1/6 or about 0.167.
Therefore, the binomial probability is:
b(2; 5, 0.167) = 5C2 * (0.167)2 * (0.833)3
b(2; 5, 0.167) = 0.161
R Code:
> dbinom(2, size=5, prob=0.167)
[1] 0.1612
STATISTICS WITH R PROGRAMMING Unit - V

Problem: In a restaurant seventy percent of people order for Chinese food and thirty percent for Italian food. A
group of three persons enter the restaurant. Find the probability of at least two of them ordering for Italian food.
Solution:-
The probability of ordering Chinese food is 0.7 and the probability of ordering Italian food is 0.3. Now, if
at least two of them are ordering Italian food then it implies that either two or three will order Italian
food.

Probability for two ordering Italian food,


P(X=2) = 3C2(0.3)2(0.7)1
= 3×0.09×0.7
= 0.189
Probability for all three ordering Italian food,
P(X=3) = 3C3(0.3)3(0.7)0
= 1×0.027×1
= 0.027
Hence, the probability for at least two persons ordering Italian food is,
P(X ≥ 2) = P(X=2)+P(X=3) = 0.189+0.027=0.216
R code:-
> dbinom(2,size=3,prob=0.3)+
+ dbinom(3,size=3,prob=0.3)
[1] 0.216

Cumulative Binomial Probability:- A cumulative binomial probability refers to the probability that the
binomial random variable falls within a specified range (e.g., is greater than or equal to a stated lower
limit and less than or equal to a stated upper limit).

Problem:What is the probability of obtaining 45 or fewer heads in 100 tosses of a coin?


Solution: To solve this problem, we compute 46 individual probabilities, using the binomial
formula. The sum of all these probabilities is the answer we seek.
Thus,
b(x < 45; 100, 0.5) = b(x = 0; 100, 0.5) + b(x = 1; 100, 0.5) + . . . + b(x = 45; 100, 0.5)
= 0.184
R code:-
> pbinom(45,size=100,prob=0.5)
[1] 0.1841008

Problem: Suppose there are twelve multiple choice questions in an English class quiz. Each question has five
possible answers, and only one of them is correct. Find the probability of having four or less correct answers if a
student attempts to answer every question at random.
Solution:
Since only one out of five possible answers is correct, the probability of
answering a question correctly by random is 1/5=0.2.
 To find the probability of having exactly 4 correct answers by
random attempts as follows.
> dbinom(4, size=12, prob=0.2)
[1] 0.1329
 To find the probability of having four or less correct answers by random attempts, we
apply the function dbinom with x = 0,…,4.
> dbinom(0, size=12, prob=0.2) + dbinom(1, size=12, prob=0.2) +
+ dbinom(2, size=12, prob=0.2) + dbinom(3, size=12, prob=0.2) +
+ dbinom(4, size=12, prob=0.2)
[1] 0.9274
 Alternatively, we can use the cumulative probability function for binomial
distribution pbinom.
STATISTICS WITH R PROGRAMMING Unit - V

> pbinom(4, size=12, prob=0.2)


[1] 0.92744
Answer:-The probability of four or less questions answered correctly by random in a twelve
question multiple choice quiz is 92.7%.

Problem: Fit an appropriate binomial distribution and calculate the theoretical distribution
x: 0 1 2 3 4 5
f: 2 14 20 34 22 8
Solution:
Here n = 5 , N = 100
Mean = ∑ xi fi = 2.84
∑ fi
np = 2.84
p = 2.84/5 = 0.568
q = 0.432

p(r) = 5Cr (0.568)r (0.432) 5-r , r = 0,1,2,3,4,5


Theoretical distributions are
Calculation of Expected Frequency as follows
r p(r) N* p(r)
0 0.0147 100 * 0.0147 =1.47 = 1
1 0.097 100 * 0.097 =9.7 =10
2 0.258 100 * 0.258 =25.8 =26
3 0.342 100 * 0.342 =34.2 =34
4 0.226 100 * 0.226 =22.6 =23
5 0.060 100 * 0.060 = 6 =6
Total = 100
R code:-
> x <- 0:5
> f <- c(2,14,20,34,22,8)
> df <-data.frame(x,f)
> fitbin <- fitdist(df$f,"nbinom")
> summary(fitbin)
Fitting of the distribution ' nbinom ' by maximum
likelihood
Parameters :
estimate Std. Error
size 2.192416 1.441296
mu 16.664004 4.886713
Loglikelihood: -22.387 AIC: 48.774 BIC: 48.35752
Correlation matrix:
size mu
size 1.0000000000 0.0003165092
mu 0.0003165092 1.0000000000

> plot(fitbin)

Poisson Distribution :- The Poisson distribution is the probability distribution of independent


event occurrences in an interval. If λ is the mean occurrence per interval, then the probability of
having x occurrences within a given interval is:
STATISTICS WITH R PROGRAMMING Unit - V

Examples:
1. The number of defective electric bulbs manufactured by a reputed company.
2. The number of telephone calls per minute at a switch board
3. The number of cars passing a certain point in one minute.
4. The number of printing mistakes per page in a large text.

R has four in-built functions to generate binomial distribution. They are described below.
 dpois(x, lambda, log = FALSE) :- This function gives the probability density distribution at each
point.
 ppois(q, lambda, lower.tail = TRUE, log.p = FALSE) :- This function gives the cumulative
probability of an event. It is a single value representing the probability.
 qpois(p, lambda, lower.tail = TRUE, log.p = FALSE):- This function takes the probability value
and gives a number whose cumulative value matches the probability value.
 rpois(n, lamda) :- This function generates required number of random values of given probability
from a given sample.
Following is the description of the parameters used −
 x is a vector of numbers.
 p is a vector of probabilities.
 n is number of observations.
 size is the number of trials.
 prob is the probability of success of each trial.

Problem:- If there are twelve cars crossing a bridge per minute on average, find the probability of having
seventeen or more cars crossing the bridge in a particular minute.
Solution:-
The probability of having sixteen or less cars crossing the bridge in a
particular minute is given by the function ppois.
> ppois(16, lambda=12) # lower tail
[1] 0.89871
Hence the probability of having seventeen or more cars crossing the
bridge in a minute is in the upper tail of the probability density function.
> ppois(16, lambda=12, lower=FALSE) # upper tail
[1] 0.10129
Answer:- If there are twelve cars crossing a bridge per minute on average, the probability of
having seventeen or more cars crossing the bridge in a particular minute is 10.1%.

Problem:- The average number of homes sold by the Acme Realty company is 2 homes per day. What is the
probability that exactly 3 homes will be sold tomorrow?
Solution: This is a Poisson experiment in which we know the following:
 μ = 2; since 2 homes are sold per day, on average.
 x = 3; since we want to find the likelihood that 3 homes will be
sold tomorrow.
 e = 2.71828; since e is a constant equal to approximately
2.71828.
We plug these values into the Poisson formula as follows:
STATISTICS WITH R PROGRAMMING Unit - V

P(x; μ) = (e-μ) (μx) / x!


P(3; 2) = (2.71828-2) (23) / 3!
= (0.13534) (8) / 6
= 0.180
R Code:-
> dpois(3,lambda = 2)
[1] 0.180447

Cumulative Poisson Probability:- A cumulative Poisson probability refers to the probability that the
Poisson random variable is greater than some specified lower limit and less than some specified upper
limit.
Problem:-Suppose the average number of lions seen on a 1-day safari is 5.
What is the probability that tourists will see fewer than four lions on the next
1-day safari?
Solution: This is a Poisson experiment in which we know the following:
 μ = 5; since 5 lions are seen per safari, on average.
 x = 0, 1, 2, or 3; since we want to find the likelihood that
tourists will see fewer than 4 lions; that is, we want the
probability that they will see 0, 1, 2, or 3 lions.
 e = 2.71828; since e is a constant equal to approximately
2.71828.
To solve this problem, we need to find the probability that tourists will see 0, 1, 2, or 3 lions. Thus,
we need to calculate the sum of four probabilities: P(0; 5) + P(1; 5) + P(2; 5) + P(3; 5). To compute
this sum, we use the Poisson formula:
P(x < 3, 5) = P(0; 5) + P(1; 5) + P(2; 5) + P(3; 5)
P(x < 3, 5) = [ (e-5)(50) / 0! ] + [ (e-5)(51) / 1! ] + [ (e-5)(52) / 2! ] + [ (e-5)(53) / 3! ]
P(x < 3, 5) = [ (0.006738)(1) / 1 ] + [ (0.006738)(5) / 1 ] + [ (0.006738)(25) / 2 ] +[ (0.006738)(125) / 6]
P(x < 3, 5) = [ 0.0067 ] + [ 0.03369 ] + [ 0.084224 ] + [ 0.140375 ]
P(x < 3, 5) = 0.2650
Thus, the probability of seeing at no more than 3 lions is 0.2650.
R Code:-
> ppois(3,lambda = 5)
[1] 0.2650259

Normal Distribution:- A continuous random variable X follows a normal distribution


with mean μ and variance σ2 is a statistic distribution with probability density function

, on the domain .
Standard Normal Distribution
It is the distribution that occurs when a normal random variable has a mean of zero and a standard
deviation of one.
The normal random variable of a standard normal distribution is called a standard score or a z score.
Every normal random variable X can be transformed into a z score via the following equation:
Z = (X - μ) / σ
where X is a normal random variable, μ is the mean, and σ is the standard deviation.
yielding

Standard Normal Curve:- One way of figuring out how data are
distributed is to plot them in a graph. If the data is evenly distributed,
you may come up with a bell curve. A bell curve has a small percentage
of the points on both tails and the bigger percentage on the inner part of
STATISTICS WITH R PROGRAMMING Unit - V

the curve. The shape of the standard normal distribution looks like
this:

> mean = median = mode


> symmetry about the center
> 50% of values less than the mean and 50% greater than
the mean

R functions:
 dnorm(x, mean = 0, sd = 1, log = FALSE) :- This function gives the probability density distribution
at each point.
 pnorm(q, mean = 0, sd = 1, lower.tail = TRUE, log.p = FALSE):- This function gives the cumulative
probability of an event. It is a single value representing the probability.
 qnorm(p, mean = 0, sd = 1, lower.tail = TRUE, log.p = FALSE):- This function takes the probability
value and gives a number whose cumulative value matches the probability value.
 rnorm(n, mean = 0, sd = 1) :- This function generates required number of random values of given
probability from a given sample.

Procedure to find probability using positive Z-score table


Case 1: Area between 0 Area(z)
and any z score

Case 2: Area in any tail 0.5 – Area(z)

Case 3: Area between two |Area(z2)-Area(z1)|


z-scores on the same side
of the mean
STATISTICS WITH R PROGRAMMING Unit - V

Case 4: Area between two Area(z1)+Area(z2)


z-scores on the opposite
side of the mean

Case 5: Area to the left of 0.5+ Area(z)


a positive Z score

Case 6: Area to the right 0.5+ Area(z)


of a negative Z score
STATISTICS WITH R PROGRAMMING Unit - V

Problem:-X is a normally normally distributed variable with mean μ = 30 and standard deviation σ = 4. Find
a) P(x < 40)
b) P(x > 21)
c) P(30 < x < 35)
Solution:
a) For x = 40, then
z = x − µ /σ
⇒z = (40 – 30) / 4
= 2.5 (=z1 say)
Hence P(x < 40) = P(z < 2.5)
= 0.5+A(z1) = 0.9938
b) For x = 21,
z = x − µ /σ
⇒z = (21 - 30) / 4
= -2.25 (= -z1 say)
Hence P(x > 21) = P(z > -2.25)
= 0.5- A(z1) = 0.9878
c) For x = 30
z = x − µ /σ ⇒,
z = (30 - 30) / 4 = 0 and
for x = 35,
z = x − µ /σ
⇒ z = (35 - 30) / 4
= 1.25
Hence P(30 < x < 35) = P(0 < z < 1.25)
= [area to the left of z = 1.25] - [area to the left of 0]
= 0.8944 - 0.5 = 0.3944

Problem:-The length of life of an instrument produced by a machine has a normal ditribution with a mean of 12
months and standard deviation of 2 months. Find the probability that an instrument
produced by this machine will last.
a) less than 7 months.
b) between 7 and 12 months.
Solution:
a) P(x < 7)
for x = 7
z = x − µ /σ
⇒z = (7 – 12) / 2
= -2.5 (=z1 say)
Hence P(x < 7) = P(z < -2.5)
= 0.0062
b) P(7 < x < 12)
For x=12
z = x − µ /σ
⇒z = (12 – 12) / 2
= 0 (=z1 say)
Hence P(7 < x < 12) = P(-2.5 < z < 0)
= 0.4938

Problem:-The Tahoe Natural Coffee Shop morning customer load follows a normal
distribution with mean 45 and standard deviation 8. Determine the probability that the
number of customers tomorrow will be less than 42.
STATISTICS WITH R PROGRAMMING Unit - V

Solution:-
We first convert the raw score to a z-score. We have
z = x − µ /σ
⇒z =(42−45)/8=−0.375
Next, we use the table to find the probability. The table gives 0.3520. (We have rounded the raw score
to -0.38).
We can conclude that
P(x<42)=P(x<-0.38)
=0.352
That is there is about a 35% chance that there will be fewer than 42 customers tomorrow.

Example:
> x <- c(92,117,109,85,117,107,82,83,119,113,101,106,101,84,126,69,82,79,84,100,104,111,109,92,93,107,
81,118,81,133,111,82,120,103,115,89,74,110,83,110,96,102,108,110,140,106,111,98,98,99,74,101,107,104,
128,87,95,109,104,91,83,98,99,103,126,123,85,98,93,100)

> h<-hist(x,col = "blue")


> m <- mean(x)
> s <- sd(x)
> xf <- seq(min(x),max(x),length=70)
> dis <- dnorm(xf,m,s)
> dis <- dis*diff(h$mids[1:2]*length(x))
> lines(xf,dis,col="red",lwd=3)

Problem:-Assume that the test scores of a college entrance exam fits a normal distribution. Furthermore,
the mean test score is 72, and the standard deviation is 15.2. What is the percentage of students scoring
84 or more in the exam?
Solution:-
We apply the function pnorm of the normal distribution with mean 72 and standard deviation
15.2. Since we are looking for the percentage of students scoring higher than 84, we are interested in
the upper tail of the normal distribution.
> pnorm(84, mean=72, sd=15.2, lower.tail=FALSE)
[1] 0.21492

Correlation:- A correlation is a relationship between two variables.


Typically, we take x to be the independent variable. We take y to be the
dependent variable. Data is represented by a collection of ordered pairs
(x,y).

This will always be a number between -1 and 1 (inclusive).


• If r is close to 1, we say that the variables are positively correlated. This means there is likely a strong
linear relationship between the two variables, with a positive slope.
•If r is close to -1, we say that the variables are negatively correlated. This means there is likely a strong
linear relationship between the two variables, with a negative slope.
•If r is close to 0, we say that the variables are not correlated. This means that there is likely no linear
relationship between the two variables, however, the variables may still be related in some other way.
To run a correlation test we type:
> cor.test(var1, var2, method = "method")
The default method is "pearson" so you may omit this if that is what you want. If you type "kendall" or
"spearman" then you will get the appropriate significance test.
STATISTICS WITH R PROGRAMMING Unit - V

Problem:- The local ice cream shop keeps track of how much ice cream they sell versus the temperature
on that day, here are their figures for the last 12 days:

Temperature 14.2 16.4 11.9 15.2 18.5 22.1 19.4 25.1 23.4 18.1 22.6 17.2
oC
Ice cream $215 $325 $185 $332 $406 $522 $412 $614 $544 $421 $445 $408
sales

Solution:-

Formula for correlation coefficient:

R Code:-
> temp <- c(14.2,16.4,11.9,15.2,18.5,22.1,19.4,25.1,23.4,18.1,22.6,17.2)
> sales <- c(215,325,185,332,406,522,412,614,544,421,445,408)
> corr_coeff <- cor(temp,sales)
> corr_coeff
[1] 0.9575066
> cov(temp,sales)
[1] 484.0932
#Adds a line of best fit to your scatter plot
> plot(temp, sales, pch=16,col="red")
>abline(lm(sales~temp),col="blue")
STATISTICS WITH R PROGRAMMING Unit - V

T-test for single mean:- One-sample t-test is used to compare the mean of a population to a
specified theoretical mean (μ).
Let X represents a set of values with size n, with mean μ and with standard deviation S.
The comparison of the observed mean (μ) of the population to a theoretical value μ is performed with
the formula below:
x  0
t 
 s n
To evaluate whether the difference is statistically significant, you first have to read in t test
table the critical value of Student’s t distribution corresponding to the significance level alpha of your
choice (5%). The degrees of freedom (df) used in this test are: df = n−1

Problem:-: A professor wants to know if her introductory statistics class has a good grasp of basic
math. Six students are chosen at random from the class and given a math proficiency test. The professor
wants the class to be able to score above 70 on the test. The six students get scores of 62, 92, 75, 68, 83,
and 95. Can the professor have 90 percent confidence that the mean score for the class on the test would
be above 70?
Solution:-
Null hypothesis: H 0: μ = 70
Alternative hypothesis: H a : μ > 70
First, compute the sample mean and standard deviation:
62  92  75  68  83  95
x
6
475
  13.17
6
 Null Hypothesis H0 : The sample meet upto standard i.e
µ >70 hours
 Alternative Hypothesis HA: µ not greater than 70,
 Level of Siginificance:   0.05
 x  0
The test statistic is t 
 s n


STATISTICS WITH R PROGRAMMING Unit - V

79.71  70 9.17
t= 
13.17 6 5.38
= 1.71(calculate value of t)
To test the hypothesis, the computed t‐value of 1.71 will be compared to the critical value in the t‐table
with 5 df is 1.67, the calculate of t is more than table value of t, so null hypothsis is rejected.
R code:-
> t.test(x,alternative="two.sided",mu=70)
One Sample t-test
data: x
t = 1.7053, df = 5, p-value = 0.1489
alternative hypothesis: true mean is not equal to 70
95 percent confidence interval:
65.34888 92.98446
sample estimates:
mean of x
79.16667

Problem:-: A Sample of 26 bulbs gives a mean life of 990 hours with S.D of 20 hours. The manufacurer
claims that the mean life of bulbs is 1000 hours. Is sample meet upto the standard.
Solution: Here n = 26,
Sample mean x̅ = 990 hours
S.D s = 20 hours
Population mean µ = 1000 hours
Df = n-1 = 26-1 = 25
 Null Hypothesis H0: The sample meet upto standard i.e µ = 1000 hours
 Alternative Hypothesis HA: µ not equal to 1000,
 Level of Siginificance:   0.05
 the test statistic is
x  0
t 
s n
t = 990-1000/20/√26
= 2.5 (calculate value of t)
Table value of t with 25 df is 1.708
The calculate value of t is more than table value of t, so null hypotheis is rejected at 5% level.

Paired comparisons( Paired t-test ):- Sometimes data comes from non independent samples. An
example might be testing "before and after" of cosmetics or consumer products. We could use a single
random sample and do "before and after" tests on each person. A hypothesis test based on these data
would be called a paired comparisons test. Since the observations come in pairs, we can study the
difference, d, between the samples. The difference between each pair of measurements is called di.

Test statistic:- With a population of n pairs of measurements, forming a simple random sample from a
normally distributed population, the mean of the difference, d , is tested using the following
implementation of t.
d  
t
S/ n

Problem :- The blood pressure of 5 women before and after intake of a certain drug are
given below: Test whether there is significant change in blood pressure at 1% level of
significance.
Before 110 120 125 132 125
After 120 118 125 136 121

12 U.Padma Jyothi, CSE Dept , VITB


STATISTICS WITH R PROGRAMMING Unit - V

Solution: Let µ be the mean of population of differences.


 Null Hypothesis H0: µ1= µ2 i,e, no change in B.P.
 Alternative Hypothesis HA: µ1≠ µ2 i,e, no change in B.P.
 Level of Siginificance:   0.01
 Computation : Differences di’s (before and after drug) are
-10,2,0,14,4
10  2  0  4  4
d
5
8
  1.6
5

1 n
S 2   (di  d )2
n 1 i1
1 5
4  (di  d )2

i1
1
 [(10 1.6)2  (2 1.6)2  (0 1.6)2  (4 1.6)2  (4 1.6)2 ]
4
123.20
  30.8
4
S  30.8  5.55
 Test statistic: The test statistic is t which is calculated as
d  
t
S/ n
  1.16  0.645
5.55 / 5
Calculated |t| value is 0.645
Tabulates t0.01 with 5-1 = 4 degrees of freedom is 3.747.
Since calculated t < t0.01 , we accept the Null hypothesis and conclude that there is no significant
change in blood pressure.
R code:-
> x <- c(110,120,125,132,125)
> y <- c(120,118,125,136,121)
> t.test(x,y,paired=TRUE)
Paired t-test
data: x and y
t = -0.64466, df = 4,
p-value = 0.5543
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
-8.490956 5.290956
sample estimates:
mean of the differences
-1.6

T-test for difference of two population means :-


With a two-sample t-test, we compare the population means to each other and again look at the
difference. We expect that x  y would be close to μ1 – μ2. The test statistic will use both sample means,
sample standard deviations, and sample sizes for the test.
A two-sample t-test follows
 Write the null and alternative hypotheses.
STATISTICS WITH R PROGRAMMING Unit - V

 State the level of significance and find the critical value. The critical value, from the
student’s t-distribution, has the lesser of n1-1 and n2 -1 degrees of freedom.
 Compute the test statistic.
 Compare the test statistic to the critical value and state a conclusion.

x y
t ~ t n1 n2 -2
1 1
S 
n1 n2
where
(x  x)2   ( y i  y)2
or S2   i
n s 2 n s 2
S  11
2 2 2
n1  n2  2 n1  n2  2

Problem:- Two horses A and B were tested according to the time (in seconds) to run a particular track
with the following results.
Horse A 28 30 32 33 33 29 34
Horse B 29 30 30 24 27 29
Test whether the two horses have the same running capacity.

Solution:- Given n1=7 and n2 = 6


We first compute the same means and standard deviations.
x  Mean of the first sample
1 1
 (28  30  32  33  33  29  34)  (219)  31.286
7 7
y  Mean of thesecond sample
1 1
 (29  30  30  24  27  29)  (169)  28.16
6 6
x xx y y y
( x  x )2 ( y  y )2
28 -3.286 10.8 29 0.84 0.7056
30 -1286 1.6538 30 1.84 3.3856
32 0.714 0.51 30 1.84 3.3856
33 1.714 2.94 24 -4.16 17.3056
33 1.714 2.94 27 -1.16 1.3456
29 -2.286 5.226 29 0.84 0.7056
34 2.714 7.366
219 31.4359 169 26.8336
 x)2   ( y i  y)
Now, S2   (xi
2

n1  n2  2
(31.4358  26.8336)
  5.23
762
Therefore S  5.23  2.3

 Null Hypothesis H0: µ1= µ2


 Alternative Hypothesis HA: µ1≠ µ2
 Level of Siginificance:   0.05
STATISTICS WITH R PROGRAMMING Unit - V


 Computation : t  x  y 
31.286 - 28.16  2.443
1 1 1 1
S  (2.3) 
n1 n2 7 6
Tabulates t0.05 with 7+6-2 = 11 degrees of freedom at 5% level of significance is 2.2
Since calculated t > t0.05 , we reject the Null hypothesis and conclude that there is no significant change in
blood pressure.

ANOVA:- (ANALYSIS OF VARIANCE)


When we have only two samples we can use the t-test to compare the means of the samples
but it might become unreliable in case of more than two samples. If we only compare two means, then
the t-test (independent samples) will give the same results as the ANOVA. Anova is performed with F-
test.

Null hypothesis H0: There are no differences among the mean values of the groups being compared
(i.e., the group means are all equal)–
H0: µ1 = µ2 = µ3 = …= µk
Alternative hypothesis H1: (Conclusion if H0 rejected)?
Not all group means are equal (i.e., at least one group mean is different from the rest).

ANOVA one-way classification:-


Step 1: Total number of all observations
T   Xij
i j

Step 2: Correlation factor


T2 T2
cf  
N rs
Step 3:Total sum of squares

 X  cf
2
TSS = S2T  ij
i j
Step 4: Treatment sum of squares
2
jT
TrSS = S2Tr  N cf
Step 5: Error sum of squares
ESS = S2E = TSS-TrSS
Source of variable d.f Sum of Squares TSS F-Test
Treatment k-1 Tj2 STr 2 S 2Tr
(between sample) S 2Tr   cf N S2Tr 
k 1
Fcal 
S 2E
Error n-k S2E = TSS-TrSS S 2E
S E 
2
nk

You might also like