Unit 1 R
Unit 1 R
A- II SEMESTER
Language-II 3+0 4 80 20
English-II 3+0 4 80 20
1 R PROGRAMMING 2024
Course Code: CA2T2 Course Title: Statistical Computing and R
Programming
Course Credits: 04
Total Contact Hours: 60
Internal Assessment : 20
Teaching Hours/Week: 04
Exam Duration : 3 Hours
Semester End Exam: 80 Marks
SYLLABUS
Marks
CA2T2: Statistical Computing and R Programming
Course Outcomes (COs):
After the successful completion of the course, the student will be able to:
[Link] fundamentals of statistical analysis in R environment.
[Link] key terminologies, concepts and techniques employed in Statistical Analysis.
[Link] Calculate, Implement Probability and Probability Distributions to solve a wide variety of problems.
[Link] and interpret a variety of Hypothesis Tests to aid Decision Making.
[Link], Analyse, and Interpret Correlation Probability and Regression to analyse the underlying relationships between different variables.
Unit-II 15
Programming: Conditions and Loops - If statements - Stand-Alone Statement, Using If Else, Nesting and Stacking Statements, The Switch
Function. Coding Loops - For Loops, While Loops, Repeat Loop, Other Control Flow Mechanisms - Declaring Break, Next and goto
statement, R-Function: function definition, Built-in functions: Basic Math function - min(), max(), sum(), sqrt(),abs(),ceiling(),floor(), trunc(),
round(), cos(), sin(), tan(), String function -
grep(), nchar() , paste(), sprintf(), substr(), strsplit(), regex() gregexpr(), toupper(), tolower(), paste(), User Defined Function, Exception
Handling, Progress and Timing, Visibility.
2 Presentation title 20XX
SYLLABUS
Unit-III 15
Statistics and Probability: Elementary Statistics, Basic data visualisation, probability, common probability distributions:
common probability mass functions - Bernoulli, Binomial, Poisson distributions, common probability density functions -
Uniform, Normal, Student’s t- distribution.
Unit-IV 15
Statistical Testing and Modelling: Sampling distributions, hypothesis testing, Analysis of variance, Simple linear
regression, multiple linear regressions. Advanced graphics: Basic Plotting, plot customization, plotting regions and
margins, point and click coordinate interaction, customizing traditional R plots, specialized text and label notation, Defining
colors and plotting in higher dimensions.
Applications of R
Facebook
Google
Twitter
7 R PROGRAMMING 2024
ADVANTAGES OF R OVER OTHER PROGRAMMING
7. Cross-Platform Compatibility
Runs Everywhere: R is platform-independent and works seamlessly on Windows, Mac, and Linux.
Seamless Cloud Integration: R integrates well with cloud computing environments for scalable data
processing.
9. Reproducible Research
R Markdown: Allows users to combine code, results, and narratives in a single document, promoting
reproducible research.
Version Control: With integration into tools like Git, R supports collaborative and reproducible projects.
12 R PROGRAMMING 2024
FEATURES OF R
R is a domain-specific programming language which aims to do data analysis. It has some unique features which
make it very powerful.
It is a simple and effective programming language which has been well developed.
It is data analysis software.
It is a well-designed, easy, and effective language which has the concepts of user-defined, looping, conditional, and various I/O
facilities.
It has a consistent and incorporated set of tools which are used for data analysis.
For different types of calculation on arrays, lists and vectors, R contains a suite of operators.
It provides effective data handling and storage facility.
It is an open-source, powerful, and highly extensible software.
It provides highly extensible graphical techniques.
It allows us to perform multiple calculations using vectors.
R is an interpreted language.
13 R PROGRAMMING 2024
INSTALLING R STUDIO
In the first step, we visit the RStudio official site and click on Download RStudio.
In the next step, we will select the RStudio desktop for open-source license and click on download.
In the next step, we will select the appropriate installer. When we select the installer, our downloading
of RStudion setup will start
In the next step, we will run our setup in the following way:
• Click on Next.
• Click on Install.
• Click on finish.
• RStudio is ready to work.
14 R PROGRAMMING 2024
R Advantages and Disadvantages
15 R PROGRAMMING 2024
Syntax of R Programming
R Script File
string <-"Hello World!"
print(string)
16 R PROGRAMMING 2024
DATA TYPES IN R
In programming languages, we need to use various variables to store various information. Variables are the
reserved memory location to store values. As we create a variable in our program, some space is reserved in
memory.
In R, there are several data types such as integer, string, etc. The operating system allocates memory based on the
data type of the variable and decides what can be stored in the reserved memory.
17 R PROGRAMMING 2024
Data type Example Description
if else repeat
NaN NA NA_integer_
19 R PROGRAMMING 2024
Variables in R Programming
Variables are used to store the information to be manipulated and referenced in the R program.
22 R PROGRAMMING 2024
OPERATORS IN R
In computer programming, an operator is a symbol which represents an action. An
operator is a symbol which tells the compiler to perform
specific logical or mathematical manipulations. R programming is very rich in built-in
operators.
Arithmetic Operators:
Arithmetic operators are the symbols which are used to represent arithmetic math
operations. The operators act on each and every element of the vector.
Operator Description Example Output
+ Addition 5+3 8
- Subtraction 5-3 2
* Multiplication 5*3 15
/ Division 5/3 1.66667
Modulus
%% 5 %% 3 2
(remainder)
c(TRUE,FALSE) |
| `Element-wise OR `c(TRUE, FALSE)
c(FALSE,FALSE)
|| Logical OR(single) `TRUE || FALSE TRUE
24 R PROGRAMMING 2024
Relational Operators:
A relational operator is a symbol which defines some kind of relation between two entities. These include numerical
equalities and inequalities. A relational operator compares each element of the first vector with the corresponding
element of the second vector. The result of the comparison will be a Boolean value
== Equal to 5 == 3 FALSE
25 R PROGRAMMING 2024
DATA STRUCTURES IN R
• Is a particular way of organizing data in a computer so that it can be used effectively.
• To reduce the space and time complexities of different tasks.
• Data structures in R programming are tools for holding multiple values.
Lists-Different types
Lists-Different types
Access Vectors
You can access the vectoExample:
r items by referring to its index You can also access multiple elements by referring
number inside brackets []. The to different index positions with the c() function:
first item has index 1, the second
item has index 2, and so on:
Example: Example:
OUTPUT
OUTP
UT
29 R PROGRAMMING 2024
Vector Data Structure in R
OUTP
UT
OUTPUT
30 R PROGRAMMING 2024
Vector Data Structure in R
Example: Example:
OUTP OUTPUT
UT
31 R PROGRAMMING 2024
Matrices Data Structure in R
A matrix is a two dimensional data set with columns and rows.
A column is a vertical representation of data, while a row is a horizontal representation of data.
A matrix can be created with the matrix() function.
Specify the nrow and ncol parameters to get the amount of rows and columns:
matrix(data,nrow=number_of_rows,ncol=number_of_colu
mns,byrow=FALSE)
Example:
OUTP
UT
32 R PROGRAMMING 2024
Matrices Data Structure in R
Example:
Access Matrix Items
You can access the items by using [
The whole row can be accessed if you specify a
] brackets. The first number "1" in the comma after the number in the bracket:
bracket specifies the row-position, while the
second number "2" specifies the column-
position:
Example:
Example:
The whole column can be accessed if you specify
a comma before the number in the bracket:
OUTP
UT
33 R PROGRAMMING 2024
Matrix Operations
You can perform various Example: Subtraction
operations on matrices-
>mat1<-
addition,subtraction,multiplication matrix(c(1,2,3,4),nrow=2)
and transposition. > mat2<-
matrix(c(5,6,7,8),nrow=2)
Example: Addition
OUTP
UT
[,1] [,2]
[1,] 23 31
[2,] 34 46
35 R PROGRAMMING 2024
Arrays Data Structure in R
• Compared to matrices, arrays can have more than two dimensions.
• We can use the array() function to create an array, and the dim parameter to specify the
dimensions
• array_name <- array(data, dim= (row_size, column_size, matrices, dim_names))
Example: OUTP
UT
36 R PROGRAMMING 2024
Accessing Array Elements
• Access elements using square brackets and specifying the indices for each dimension
Example:
> arr<-array(c(1,2,3,4,5,6,7,8,9,10,11,12),dim=c(2,3,2))
> print(arr)
,,1
[,1] [,2] [,3] Accessing
[1,] 1 3 5
[2,] 2 4 6 > element<-arr[1,2,1]
> print(element)
,,2 OUTP
UT
[,1] [,2] [,3] [1] 3
[1,] 7 9 11
[2,] 8 10 12
37 R PROGRAMMING 2024
Array Operations
• Perform various operations on arrays,such as addition,subtraction,multiplication and more
Use the dim() function to find the amount of rows and columns in an array:
Example: OUTP
UT
39 R PROGRAMMING 2024
Arrays Functions
Array Length
Example:
OUTP
UT
40 R PROGRAMMING 2024
List Data Structure in R
• Lists are heterogeneous data structures.
• They are very similar to vectors except they can store data of different types.
• To create a list, we use the list() function.
Example:
OUTP
UT
41 R PROGRAMMING 2024
Accessing List
Access Lists Change Item Value
You can access the list items by referring to To change the value of a specific item, refer to the
its index number, inside brackets. index number:
The first item has index 1, the second item
has index 2, and so on: OUTP
Example: UT
> name<-
my_list$name
> print(name)
[1] "alice"
42 R PROGRAMMING 2024
Accessing List
Example:
> my_list<-
list(name="alice",age=30,student=TRUE,grades=c(95,88,75)) > name<-
>print(my_list) my_list$name
>print(name)
$name
[1] "alice" [1] "alice"
$age
[1] 30
$student my_list[["name"]
[1] TRUE ]
43 R PROGRAMMING 2024
List Data Structure in R
Example:
>my_list$new_element<-"New data" > my_list[["new_elemnt2"]]<-"More data"
>print(my_list) > print(my_list)
$name
$name [1] "alice"
[1] "alice" $age
$age [1] 30
[1] 30 $student
[1] TRUE
$student
$grades
[1] TRUE [1] 95 88 75
$grades $new_element
[1] 95 88 75 [1] "New data"
$new_element $new_elemnt2
[1] "More data"
[1] "New data"
44 R PROGRAMMING 2024
List Data Structure in R
> my_list$new_element<-NULL
> print(my_list)
$name
[1] "Alice"
$age
[1] 30
$student
[1] TRUE
$grades
[1] 95 88 75
$new_element2
[1] "More data"
45 R PROGRAMMING 2024
List Data Structure in R
Add List Items Remove List Items
To add an item to the end of the list, use You can also remove list items. The following example
the append() function: creates a new, updated list without an "apple" item:
Example: OUTP
UT
46 R PROGRAMMING 2024
List Data Structure in R
Example: OUTP
UT
47 R PROGRAMMING 2024
Data Frame Data Structure
48 R PROGRAMMING 2024
Data Frame Data Structure
ACCESSING DATA
Example: FRAME
> Data_Frame<-
[Link](Training=c("strength","stamina","other"),pulse=c(100,150,120),Duration=
c(60,30,45))
OUTPUT
> print(Data_Frame)
>OUTPUT
a<-[Link](Data_Frame$Training)
> print(a)
Data_Frame.Training
1 strength
2 49 stamina R PROGRAMMING 2024
3 other
Data Frame Data Structure
ACCESSING DATA
Example:
You can access individual column
FRAME
> colu<-
of a data frame by $ operator or Data_Frame[,c('Training','Pulse’)
by using square bracket[]. The $ ]OUTPUT
>colu
operator extracts a column by
name, while square brackets allow Training Pulse
to select one or more columns.
1 Strength 100
2 Stamina 150
3 other 120
> head(Data_Frame)
OUTPTraining pulse Duration
UT 1 Strength 100 50
2 Stamina 150 30
3 Other 120 20
> head(Data_Frame,2)
OUTP
Training pulse Duration
UT
1 Strength 100 50
50 2 Stamina 150 30 R PROGRAMMING 2024
Data Frame-Adding and Removing Columns
ACCESSING DATA
Example:
To add new columns use <-
FRAME
> Data_Frame$Limit<-NULL
Data_Frame
OUTPUT
Training Pulse Duration
1 Strength 100 30
2 Stamina 150 40
3 51Other 120 20 R PROGRAMMING 2024
Data Frame-Functions
To view dimensions—dim Example:
To view column names-names
names(Data_Frame)
To view in detail-str OUPUT
[1] "Training" "Pulse" "Duration“
Example:
Some of the special values in R are NA, Inf, -Inf, 2. Inf and -Inf (Infinity)
and NaN. If a computation results in a number
1. NA(Not Available) that is too big.
In R, the NA values are used to represent R will return Inf for positive number and –Inf
missing values. for negative number.
53 R PROGRAMMING 2024
Special Values in R
54 R PROGRAMMING 2024
Special Values
Four special values in R,used to check the data in any existing data set, used for data
analysis,data manipulation and programming in R
1. NA—used to represent missing or undefined value in R data set. To indicate the
absence of data for particular variable
Types-NA_integer,NA_real,NA_character_,NA_complex_ used to represent missing
values of specific data types(integer,numeric,character,complex)
NA_ for various datatypes
NA for factors-used to indicate missing levels.
2. NULL—to represent empty data similar to NA. Used in function arguments or as
a placeholder when to create an emply DS.
3.-NaN- to represent Not a [Link] represent undefined or unrepresentable
numeric values. Example:
4. Inf- to represent infinite value. –Inf represents negative infinity. > a<-NaN
Used for numeric calculations, that exceed the range of finite numbers. > [Link](a)
[1] TRUE
> length(a)
[1] 1
>
55 R PROGRAMMING 2024
Handling missing values using Special Values in R
56 R PROGRAMMING 2024
Coercion in R
Coercion includes type conversion . Type conversion means change of one type of data into another
type of data. We have two type of coercion :
1. Implicit Coercion
2. Explicit Coercion
Explicit Coercion :
In explicit coercion , we can change one
data type to another data type by applying
function.
We create an object “x” which stores integer
values from 1
to 6.
x<-0:6
We can check data type of “x” object.
class(x)
We used [Link]() to change integer data
type to numeric data type.
z<-[Link](x)
We check
57
data type of z. It shows “numeric”
R PROGRAMMING 2024
data type.
Coercion in R
Explicit Coercion :
[Link](): Converts to character data type
[Link](): Converts to numeric data type
[Link](): Converts to integer data type
[Link]():Converts to logical data type
[Link]():Converts to factor data type
[Link](): Converts to data frame data type
58 R PROGRAMMING 2024
Coercion in R
Implicit Coercion :
We input logical and numeric data in an object . Logical data convert to numeric
data implicitly.
59 R PROGRAMMING 2024
Coercion in R
Implicit Coercion :
We input logical and numeric data in an object . Logical data convert to numeric
data implicitly.
60 R PROGRAMMING 2024
R Classes and Objects
Output:
62 R PROGRAMMING 2024
S4 Class in R
S4 class is an improvement over the S3 class. They have a formally defined structure which helps in making
objects of the same class look more or less similar.
In R, we use the setClass() function to define a class. For example,
Example:
63 R PROGRAMMING 2024
Reference Class in R
• Reference classes were introduced later, compared to the other
two.
• It is more similar to the object oriented programming we
are used to seeing in other major programming
languages.
• Defining a reference class is similar to defining a S4 class.
• Instead of setClass() we use the setRefClass() function
64 R PROGRAMMING 2024
Readingand WritingFiles
R can read data from a variety of file formats—for example, files created as text, or in Excel, SPSS or Stata.
•We will mainly be reading files in text format .txt or
.csv (comma-separated, usually created in Excel).
•To read an entire data frame directly, the external file will normally have a special form
The first line of the file should have a name for each
variable in the data frame.
•Each additional line of the file has as its first item a row label and the values for each variable.
65 R PROGRAMMING 2024
66 R PROGRAMMING 2024
To find out what your current working directory is, type
•getwd()
It’s also possible to write csv files using the functions [Link]().
The syntax is as follow:
[Link](my_data, file = "my_data.csv")