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

Unit 1 R

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

Unit 1 R

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

B.C.

A- II SEMESTER
Language-II 3+0 4 80 20

English-II 3+0 4 80 20

CA2T1 Data Structures Using C 4+0 4 80 20


II
CA2T2 Statistical Methods using R 4+0 4 80 20
Programming

CA2T3 Operating System Concepts 4+0 4 80 20

CA2P1 Data Structures Lab 0+2 4 40 10

CA2P2 R Programming Lab 0+2 4 40 10

Constitutional Values-II 2+0 2 40 10

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.

Course Content Hours


Unit-I 15
The Language: Introduction – Advantages of R over Other Programming Languages, R Studio: R script file, Handling Packages in R:
Installing R Package, Syntax, Comments, Operators, R Keywords, R Data Types - numeric, Integer, logical, complex, character and raw,
Variables, Input and Output statement, Data Structures – Strings, Vectors, Matrices, Arrays, Non-numeric Values, Lists and Data Frames,
Special Values, Classes, and Coercion, Reading and Writing Files.

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.

3 Presentation title 20XX


Course Code: CA2P2 Course Title: R Programming Lab

Course Credits: 02 Teaching Hours/Week: 04


Total Contact Hours: 60 Exam Duration : 3 Hours
Internal Assessment : 10 Marks Semester End Exam: 40 Marks

CA2P2: R Programming Lab


Section-A
[Link] a R program that includes various data types in R.
[Link] a R program for different types of data structures in R
[Link] a R program that includes linear algebra operations on vectors and matrices.
[Link] a R program that includes various looping statements.
[Link] a R program for quick sort implementation, binary search tree.
[Link] a R program for calculating cumulative sums, products, minima, maxima and calculus.
[Link] a R program for finding stationary distribution of Markanov chains.
[Link] a R program for any visual representation of an object with creating graphs using graphic functions: Plot(),Hist(), Linechart(),Pie(),Boxplot(),Scatterplots().
[Link] a R program with any dataset containing data frame objects, indexing, and subsetting data frames, and employ manipulating and analyzing data.
[Link] a program to create any application of Linear Regression in a multivariate context for predictive purposes.
Section-B
•Write a R program to take input from the user (name, age, address, city, state) and display the values. Also, print the version of the R installation.
•Write a R program that includes different operators.
•Write a R program to default values for arguments, returning complex objects.
•Write a R program to create and store an array of 4 × 4 matrix and calculate its sum
•Write a R program that includes various if statements.
•Write a R program to calculate both simple interest and compound interest using functions.
•Write a R program to implement various statistical functions in R.
•Write a R program to find Correlation and Covariance.
•Write a R program to import the data set and perform an ANOVA test.
•Write a R program to define colors in various ways. (Use of named colors, RGB colors, hexadecimal color codes, and the colors()).

4 Presentation title 20XX


PROGRAMMING

Robert Gentleman Ross Ihaka

• R language was created by Ross Ihaka and Robert


Gentleman
• R is named partly after the first names of the first two R
authors
5 Presentation title 20XX
• It is an open source project and free software,
• R runs on all platforms.
• R software environment is written primarily in C,FORTRAN,
• R is an implementation of the S programming language,
• It is mostly used in the field of statistics, data miners, data analysis,
• R is a programming language and software environment for
statistical computing and graphics supported by the R Foundation.
• Other similar languages such as APL and MATLAB.

6 Presentation title 20XX


INTRODUCING TO R
 R is a software environment which is used to analyze statistical information and graphical representation. R allows
us to do modular programming using functions.
 R is an interpreted computer programming language which was created by Ross Ihaka and Robert Gentleman at the
University of Auckland, New Zealand.
 R not only allows us to do branching and looping but also allows to do modular programming using functions. R
allows integration with the procedures written in the C, C++, .Net, Python, and FORTRAN languages to improve
efficiency.

Applications of R
 Facebook
 Google
 Twitter

7 R PROGRAMMING 2024
ADVANTAGES OF R OVER OTHER PROGRAMMING

8 Presentation title 20XX


ADVANTAGES OF R OVER OTHER PROGRAMMING
[Link] for Data Analysis and Statistics
•Built-in Statistical Functions: R is specifically designed for statistical computation, providing a rich set of built-in statistical and
mathematical functions.
•Comprehensive Libraries: It includes a vast array of packages (like ggplot2, dplyr, and caret) tailored for advanced statistical
modeling and data analysis.

2. Powerful Data Visualization


Advanced Graphics: R excels in creating detailed and customizable plots and visualizations using libraries like ggplot2 and lattice.
Interactive Visualizations: Tools like Shiny and plotly enable creating interactive dashboards and web applications for data
exploration.

3. Open Source and Free


Cost-Effective: R is completely free and open source, making it accessible to individuals and organizations of all sizes.
Community Contributions: Thousands of contributors worldwide constantly expand R's capabilities with new packages and tools.

9 Presentation title 20XX


4. Rich Ecosystem of Packages
CRAN Repository: R boasts a comprehensive repository of packages (Comprehensive R Archive Network - CRAN),
covering a wide range of data analysis needs.
Domain-Specific Packages: Whether it’s genomics, finance, or machine learning, R has specialized packages for domain-
specific tasks.

5. Strong Community Support


Large User Base: R has an active and supportive community that shares knowledge through forums, blogs, and
conferences.
Documentation: Extensive documentation and tutorials make it easy for beginners and experts alike to learn and use R.

6. Flexibility and Extensibility


Supports Big Data: With integrations like SparkR and dplyr for databases, R handles large-scale data effectively.
Extensible via Other Languages: R can integrate with C++, Python, and Java for performance optimization and additional
functionality.

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.

10 Presentation title 20XX


8. Machine Learning and AI
Rich ML Libraries: R provides packages like caret, mlr, and h2o for implementing machine learning models and
pipelines.
Cutting-Edge Research: Being widely used in academia and research, R often gets state-of-the-art techniques
implemented early.

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.

10. High-Quality Reporting


Integration with LaTeX: R can produce publication-quality reports and documents.
Dynamic Reporting: Tools like R Markdown and Shiny enable creating dynamic and interactive reports.

11 Presentation title 20XX


FEATURES OF R

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

Logical True, False It is a special data type for data


with only two possible values
which can be construed as
true/false.

Numeric 12,32,112,5432 Decimal value is called numeric in


R, and it is the default
computational data type.

Integer 3L, 66L, 2346L Here, L tells R to store the value


as an integer,

Complex Z=1+2i, t=7+3i A complex value in R is defined as


the pure imaginary value i.

Character 'a', '"good'", "TRUE", '35.4' In R programming, a character is


used to represent string values.
We convert objects into character
values with the help
[Link]() function.

Raw A raw data type is used to holds


raw bytes.
18 R PROGRAMMING 2024
Keywords in R Programming
Keyword is a reserved words which is reserved by a program because it has a special meaning.

if else repeat

while function for

next break TRUE

FALSE NULL Inf

NaN NA NA_integer_

NA_real_ NA_complex_ NA_character_

19 R PROGRAMMING 2024
Variables in R Programming
Variables are used to store the information to be manipulated and referenced in the R program.

1. Variable names must start with a letter or a dot:


Valid: x, .myVar
Invalid: 1x, @var
2. Variable names can contain letters, numbers,
underscores, and dots:
Valid: var1, my_var, [Link]
Invalid: var@name
[Link] names cannot be R reserved keywords:
Invalid: if, TRUE, function, else
4. No Space in between the names
Invalid:var name, my var
20 Presentation title 2024
Variables in R Programming
Name of variable Validity Reason for valid and invalid

_var_name Invalid Variable name can't start with an


underscore(_).

var_name, [Link] Valid Variable can start with a dot, but


dot should not be followed by a
number. In this case, the variable
will be invalid.
var_name% Invalid In R, we can't use any special
character in the variable name
except dot and underscore.

2var_name Invalid Variable name cant starts with a


numeric digit.

.2var_name Invalid A variable name cannot start with


a dot which is followed by a digit.

var_name2 Valid The variable contains letter,


number and underscore and starts
with a letter.
21 Presentation title 2024
Assignment of variable
 In R programming, there are three operators which we can use to assign the values to the variable. We can use
leftward, rightward, and equal_to operator for this purpose.
 There are two functions which are used to print the value of the variable i.e., print() and cat().
# Assignment using equal operator.
variable.1 = 124
# Assignment using leftward operator.
variable.2 <- "Learn R Programming"
# Assignment using rightward operator.
133L -> variable.3
print(variable.1)
cat ("variable.1 is ", variable.1 ,"\n")
cat ("variable.2 is ", variable.2 ,"\n")
cat ("variable.3 is ", variable.3 ,"\n")

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

^ or ** Exponentiation 5^3 or 5**3 125

Modulus
%% 5 %% 3 2
(remainder)

23 %/% Integer Division 5 %/%Presentation


3 title 1 2024
Logical Operators
The logical operators allow a program to make a decision on the basis of multiple conditions. In the program, each
operand is considered as a condition which can be evaluated to a false or true value.

Operator Description Example Output

c(TRUE, FALSE) &


& Element-wise AND TRUE FALSE
c(TRUE, TRUE)

Logical AND (single


&& TRUE && FALSE FALSE
evaluation)

c(TRUE,FALSE) |
| `Element-wise OR `c(TRUE, FALSE)
c(FALSE,FALSE)
|| Logical OR(single) `TRUE || FALSE TRUE

! Logical NOT !TRUE FALSE

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

Operator Description Example Output

== Equal to 5 == 3 FALSE

!= Not equal to 5 != 3 TRUE

> Greater than 5>3 TRUE

< Less than 5<3 FALSE

Greater than or equal


>= 5 >= 3 TRUE
to

<= Less than or 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.

 Vectors-Ordered Collection of same type

 Lists-Different types

 Matrices-2 dimensional collection of same type

 Arrays-Multi Dimensional Collection of elements

 DataFrames-Table-row & column with different types

 Factors-Represent categorical data

 Tibbles-Enhanced DataFrames with modern features & printing


behavior
26 Presentation title 20XX
DATA STRUCTURE

• A data structure is a format for organizing and storing data


• They are used to store data in an organized fashion to make data manipulation and
other data operations more efficient.
• R has many data structures as follows:
 Vectors-Ordered Collection of same type

 Lists-Different types

 Matrices-2 dimensional collection of same type

 Arrays-Multi Dimensional Collection of elements

 DataFrames-Table-row & column with different


types

 Factors-Represent categorical data

 Tibbles-Enhanced DataFrames with modern


features & printing
behavior
27 Presentation title 20XX
. Vector Data Structure in R
• A vector is a basic data structure in R that consists of a
collection of data elements composed of similar basic data
types.
• Vectors are single-dimensional, homogeneous data structures.
• To create a vector, use the c() function
• Vector types-Numeric,character,Logical
Example: Example: Example:
In the example below, we create a In this example, we create a vector To create a vector with numerical
vector variable called fruits, that values in a sequence, use
that combines numerical values:
combine strings: the : operator:

OUTP OUTPU OUTPUT


UT T
28 R PROGRAMMING 2024
Vector Data Structure in R

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

You can also use negative index numbers to Change an Item


access all items except the ones specified: To change the value of a specific item, refer to the index
number:
Example: Example:

OUTP
UT
OUTPUT

30 R PROGRAMMING 2024
Vector Data Structure in R

Vector Length Sort a Vector


To find out how many items a To sort items in a vector
vector has, use alphabetically or numerically,
the length() function: use the sort() function:

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

> add<- >mat1<-


mat1+mat2 matrix(c(1,2,3,4),nrow=2)
> print(add)
>mat1<- > mat2<-
sub<-mat1-
matrix(c(1,2,3,4),nrow=2) matrix(c(5,6,7,8),nrow=2)
mat2
> mat2<- > print(sub)
matrix(c(5,6,7,8),nrow=2)
OUTP OUTP
UT [,1] UT [,1]
[,2] [,2]
[1,] 6 [1,] -4 -
10 4
34 R PROGRAMMING 2024
[2,] 8 [2,] -4 -
Matrix Operations
You can perform various
Example: Transposition
operations on matrices- > mat<-
addition,subtraction,multiplication matrix(c(1,2,3,4,5,6),nrow=2,byrow=TR
UE)
and transposition. > transposedmat<-t(mat)
> print(transposedmat)
Example: Multiplication

>mat1<- [,1] [,2]


matrix(c(1,2,3,4),nrow=2) [1,] 1 4
>
> mat2<-
mul<- [2,] 2 5
matrix(c(5,6,7,8),nrow=2)
mat1%*%mat2 [3,] 3 6
> print(mul)

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

• Array indices in R start from 1 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

• Operations perform on element-wise like matrices OUTP


, ,UT
1 ,,1
Example:
[,1] [,2] [,3] [,1] [,2] [,3]
> arr<-array(1:12,dim=c(2,3,2)) [1,] 14 18 22
[1,] -12 -12 -
[2,] 16 20 24
> arr1<-array(13:24,dim=c(2,3,2)) 12
> add<-arr+arr1 ,,2 [2,] -12 -12 -
> print(add) 12
[,1] [,2] [,3]
[1,] 26 30 34
[2,] 28 32 36 ,,2

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


> sub<-arr-arr1
[1,] -12 -12 -
> print(sub)
12
[2,] -12 -12 -
12
38 R PROGRAMMING 2024
Arrays Functions
Amount of Rows and Columns

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

Use the length() function to find the dimension of an array:

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 ]

$grades [1] "alice"


[1] 95 88 75

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

Check if Item Exists


List Length To find out if a specified item is present in a list,
To find out how many items a list has, use use the %in% operator:
the length() function:

Example: OUTP
UT

47 R PROGRAMMING 2024
Data Frame Data Structure

Data Frames are data displayed in a format as a table.


Data Frames can have different types of data inside it. While the first column can
be character, the second and third can be numeric or logical. However, each column should
have the same type of data.
Use the [Link]() function to create a data frame:
Example: OUTP
UT

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)

Training pulse Duration


1 strength 100 60
2 stamina 150 30
3 other 120 45

>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

assignment operator. To remove > Data_Frame$Limit<-c(12,13,14)


>Data_Frame
column use NULL value. OUTPUT
Example: Training Pulse Duration Limit
 Data_Frame 1 Strength 100 30 12
2 Stamina 150 40 13
Training Pulse Duration Limit 3 Other 120 20 14
1 Strength 100 30 12
2 Stamina 150 40 13
3 Other 120 20 14

> 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:

> Data_Frame  dim(Data_Frame)


Training Pulse Duration OUTPUT
1 Strength 100 30 [1] 3 3
2 Stamina 150 40
3 Other 120 20
>str(Data_Frame)
OUTPUT

'[Link]': 3 obs. of 3 variables:


$ Training: chr "Strength" "Stamina"
"Other"
$ Pulse : num 100 150 120
$ Duration: num 30 40 20
52 R PROGRAMMING 2024
Special Values in R

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

3. NaN (Not a Number)


Sometimes a computation will produce a
results which makes little sense.
In such cases R will return NaN.

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

Missing Values in R, are handled with the use of


some pre-defined functions:

[Link]() Function for Finding Missing values: It


returns a Boolean value. If NA is present in a vector
it returns TRUE else FALSE.

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

[Link]-Converts the object to double precision type


[Link]-Converts the object to complex type
[Link]-It accepts only dictionary type or vector

58 R PROGRAMMING 2024
Coercion in R

Implicit Coercion :

When type conversion occurs by itself in R.


We input numeric and character data in an object . R converts numeric data to
character data by itself.

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 :

When type conversion occurs by itself in R.


We input numeric and character data in an object . R converts numeric data to
character data by itself.

We input logical and numeric data in an object . Logical data convert to numeric
data implicitly.

60 R PROGRAMMING 2024
R Classes and Objects

Blueprint or a data type of an object. R has 3 class system-S3,S4 and Reference


-Define the structure and behavior of objects, to group data and functions together as a single unit
-Flexible and extensible system for defining and using classes.

R is a functional language that uses concepts of objects and classes.


•An object is simply a collection of data (variables) and methods (functions).
Similarly, a class is a blueprint for that object.
Class System in R
While most programming languages have a single class system, R has
three class systems:
•S3 Class
•S4 Class
•Reference Class
61 R PROGRAMMING 2024
R Classes and Objects
S3 Class in R
S3 class is the most popular class in the R programming language. Most of the classes that come predefined in
R are of this type.
Example:

Notice the creation of class, class(student1) <-


"Student_Info“
Here, Student_Info is the name of the class.
And to create an object of this class, we have
passed the student1 list inside class().
Finally, we have created an object of the
Student_Info class and called the object
student1.

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:

Here, we have created an S4 class


named Student_Info using
the setClass() function and an object
named student1 using
Output: the new() function.

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.

Code to import the file in to the software:


myData = [Link]("[Link]", header =
FALSE)print(myData)

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")

67 Presentation title 20XX

You might also like