SlideShare a Scribd company logo
INTRODUCTION TO R
(DATA VISUALIZATION)
Dr. P. Rambabu, M. Tech., Ph.D., F.I.E.
19-Feb-2022
Topics
1. Overview and about R
2. R Studio Installation
3. Fundamentals of R Programming
a) Data Structures and Data Types
b) Operators
c) Control Statements
d) Loop Statements
e) Functions
4. Descriptive Analysis using R
a) Maximum, Minimum, Range
b) Mean, Median and Mode
c) Variance, Standard Deviation
d) Quantiles, IQR
e) Summary
Introduction to R
“R” is a programming language and software environment for Statistical analysis, Graphics
Representation and Reporting.
R was first implemented in the early 1990's by Ross Ihaka and Robert Gentleman at the
University of Auckland, New Zealand, and it is currently developed by the R Development
Core Team.
R is freely available under the GNU General Public License, and pre-compiled binary
versions are provided for various operating systems like Linux, Windows and Mac.
Installation of R
Step 1: Go to CRAN R project website.
Step 2: Click on the Download R for Windows link.
Step 3: Click on the base subdirectory link or install R for the first time link.
Step 4: Click Download R X.X.X for Windows and save the executable .exe file.
Step 5: Run the .exe file and follow the installation instructions.
a) Select the desired language and then click Next.
b) Read the license agreement and click Next.
c) Select the components to install (it is recommended to install all the components). Click Next.
d) Enter/browse the folder/path you wish to install R into and then confirm by clicking Next.
e) Select additional tasks like creating desktop shortcuts etc. then click Next.
f) Wait for the installation process to complete.
g) Click on Finish to complete the installation.
Installation of RStudio
Install RStudio on Windows
Step 1: With R-base installed, let’s move on to installing RStudio. To begin, go to download
RStudio and click on the download button for RStudio desktop.
Step 2: Click on the link for the windows version of RStudio and save the .exe file.
Step 3: Run the .exe and follow the installation instructions.
a) Click Next on the welcome window.
b) Enter/browse the path to the installation folder and click Next to proceed.
c) Select the folder for the start menu shortcut or click on do not create shortcuts and then click Next.
d) Wait for the installation process to complete.
e) Click Finish to end the installation.
"Hello, World!" Program
Depending on the needs, you can program either at R command prompt or you can use an R script file to write your
program.
# My first program in R Programming (using R Script File)
myString <- "Hello, World!"
print(myString)
Output:
[1] "Hello, World!“
R does not support multi-line comments but you can perform a trick which is something as follows:
if (FALSE)
{
"This is a demo for multi-line comments and it should be put inside either a single OR double quote”
}
Variable:
Variable Assignment:
The variables can be assigned values using leftward, rightward and equal to operator. The values of the
variables can be printed using print() or cat() function. The cat() function combines multiple items into a
continuous print output.
# Assignment using equal operator.
var.1 = c(0,1,2,3)
# Assignment using leftward operator.
var.2 <- c("learn","R")
# Assignment using rightward operator.
c(TRUE,1) -> var.3
print(var.1)
cat ("var.1 is ", var.1 ,"n")
cat ("var.2 is ", var.2 ,"n")
cat ("var.3 is ", var.3 ,"n")
When we execute the above code, it produces the following result −
Note − The vector c(TRUE,1) has a mix of logical and numeric class. So logical class is coerced to numeric
class making TRUE as 1.
Data Type of a Variable:
In R, a variable itself is not declared of any data type, rather it gets the data type of the R - object assigned to it.
So R is called a dynamically typed language, which means that we can change a variable’s data type of the
same variable again and again when using it in a program.
var_x <- "Hello"
cat("The class of var_x is ",class(var_x),"n")
var_x <- 34.5
cat(" Now the class of var_x is ",class(var_x),"n")
var_x <- 27L
cat(" Next the class of var_x becomes ",class(var_x),"n")
When we execute the above code, it produces the following result −
The class of var_x is character
Now the class of var_x is numeric
Next the class of var_x becomes integer
Data Structures
In contrast to other programming languages like C and java in R, the variables are
not declared as some data type. The variables are assigned with R-Objects and the
data type of the R-object becomes the data type of the variable. There are many
types of R-objects. The frequently used ones are −
• Vectors
• Lists
• Matrices
• Arrays
• Factors
• Data Frames
The simplest of these objects is the vector object and there are six data types of
these atomic vectors, also termed as six classes of vectors. The other R-Objects are
built upon the atomic vectors.
Data Type Example
1. Logical True, False
2. Numerical 12.3, 5, 99
3. Integer 2L, 34L, 0L
4. Complex 3 + 2i
5. Character 'a' , '"good", "TRUE", '23.4'
6. Raw "Hello" is stored as 48 65 6c 6c 6f
Unit 1 - R Programming (Part 2).pptx
Unit 1 - R Programming (Part 2).pptx
Vectors
In R programming, the very basic data types are the R-objects called vectors which hold elements of different classes (Data Types).
Vectors:
When you want to create vector with more than one element, you should use c() function which means to combine the elements into a
vector.
Vector Manipulation
Vector Arithmetic
Two vectors of same length can be added, subtracted, multiplied or divided giving the result as a vector
output.
# Create two vectors.
v1 <- c(3,8,4,5,0,11)
v2 <- c(4,11,0,8,1,2)
# Vector addition.
add.result <- v1+v2
print(add.result)
# Vector subtraction.
sub.result <- v1-v2
print(sub.result)
# Vector multiplication.
multi.result <- v1*v2
print(multi.result)
# Vector division.
divi.result <- v1/v2
print(divi.result)
When we execute the above code, it produces the following result −
[1] 7 19 4 13 1 13
[1] -1 -3 4 -3 -1 9
[1] 12 88 0 40 0 22
[1] 0.7500000 0.7272727 Inf 0.6250000 0.0000000 5.5000000
Vector Manipulation
Vector Element Sorting
Elements in a vector can be sorted using the sort() function.
When we execute the above code, it produces the
following result −
v <- c(3,8,4,5,0,11, -9, 304)
# Sort the elements of the vector.
sort.result <- sort(v)
print(sort.result)
# Sort the elements in the reverse order.
revsort.result <- sort(v, decreasing = TRUE)
print(revsort.result)
# Sorting character vectors.
v <- c("Red","Blue","yellow","violet")
sort.result <- sort(v)
print(sort.result)
# Sorting character vectors in reverse order.
revsort.result <- sort(v, decreasing = TRUE)
print(revsort.result)
[1] -9 0 3 4 5 8 11 304
[1] 304 11 8 5 4 3 0 -9
[1] "Blue" "Red" "violet" "yellow"
[1] "yellow" "violet" "Red" "Blue"
Lists
A list is an R-object which can contain many different types of elements inside it like vectors,
functions and even another list inside it.
When we execute the above code, it produces the following result −
# Create a list.
list1 <- list(c(2,5,3),21.3,sin)
# Print the list.
print(list1)
[[1]]
[1] 2 5 3
[[2]]
[1] 21.3
[[3]] function (x) .Primitive("sin")
Naming List Elements
The list elements can be given names and they can be accessed using these
names.
# Create a list containing a vector, a matrix and a list.
list_data <- list(c("Jan","Feb","Mar"), matrix(c(3,9,5,1,-2,8), nrow = 2),
list("green",12.3))
# Give names to the elements in the list.
names(list_data) <- c("1st Quarter", "A_Matrix", "A Inner list")
# Show the list.
print(list_data)
When we execute the above code, it produces the following result −
Manipulating Lists
We can add, delete and update list elements as shown below. We can add and delete elements only at the
end of a list. But we can update any element.
When we execute the above code, it
produces the following result −
# Create a list containing a vector, a matrix and a list.
list_data <- list(c("Jan","Feb","Mar"),
matrix(c(3,9,5,1,-2,8), nrow = 2),
list("green",12.3))
# Give names to the elements in the list.
names(list_data) <- c("1st Quarter",
"A_Matrix", "A Inner list")
# Add element at the end of the list.
list_data[4] <- "New element"
print(list_data[4])
# Remove the last element.
list_data[4] <- NULL
# Print the 4th Element.
print(list_data[4])
# Update the 3rd Element.
list_data[3] <- "updated element"
print(list_data[3])
Converting List to Vector
A list can be converted to a vector so that the elements of the vector can be used for further manipulation. All
the arithmetic operations on vectors can be applied after the list is converted into vectors. To do this
conversion, we use the unlist() function. It takes the list as input and produces a vector.
When we execute the above code, it produces the following result −
# Create lists.
list1 <- list(1:5)
print(list1)
list2 <-list(10:14)
print(list2)
# Convert the lists to vectors.
v1 <- unlist(list1)
v2 <- unlist(list2)
print(v1)
print(v2)
# Now add the vectors
result <- v1+v2
print(result)
Merging Lists
You can merge many lists into one list by placing all the lists inside one list() function.
When we execute the above code, it produces the
following result −
# Create two lists.
list1 <- list(1,2,3)
list2 <- list("Sun","Mon","Tue")
# Merge the two lists.
merged.list <- c(list1,list2)
# Print the merged list.
print(merged.list)
Matrices
A matrix is a two-dimensional rectangular data set. It can be created using a vector input to
the matrix function.
When we execute the above code, it produces the following result −
# Create a matrix.
M = matrix( c('a','a','b','c','b','a'), nrow = 2, ncol = 3, byrow = TRUE)
print(M)
Accessing Elements of Matrix
Elements of a matrix can be accessed by using the column and row index of the element. We consider the
matrix P above to find the specific elements below
When we execute the above code, it
produces the following result −
# Define the column and row names.
rownames = c("row1", "row2", "row3", "row4")
colnames = c("col1", "col2", "col3")
# Create the matrix.
P <- matrix(c(3:14), nrow = 4, byrow = TRUE, dimnames
= list(rownames, colnames))
# Access the element at 3rd column and 1st row.
print(P[1,3])
# Access the element at 2nd column and 4th row.
print(P[4,2]) # Access only the 2nd row.
print(P[2,])
# Access only the 3rd column.
print(P[,3])
Matrix Computations
Various mathematical operations are performed on the matrices using the R operators. The result of the
operation is also a matrix. The dimensions (number of rows and columns) should be same for the matrices
involved in the operation.
Matrix Addition & Subtraction
When we execute the above code, it produces the following result −
# Create two 2x3 matrices.
matrix1 <- matrix(c(3, 9, -1, 4, 2, 6), nrow = 2)
print(matrix1)
matrix2 <- matrix(c(5, 2, 0, 9, 3, 4), nrow = 2)
print(matrix2)
# Add the matrices.
result <- matrix1 + matrix2
cat("Result of addition","n")
print(result)
# Subtract the matrices
result <- matrix1 - matrix2
cat("Result of subtraction","n")
print(result)
Matrix Computations
Matrix Multiplication & Division
When we execute the above code, it produces the following result −
# Create two 2x3 matrices.
matrix1 <- matrix(c(3, 9, -1, 4, 2, 6), nrow = 2)
print(matrix1)
matrix2 <- matrix(c(5, 2, 0, 9, 3, 4), nrow = 2)
print(matrix2)
# Multiply the matrices.
result <- matrix1 * matrix2
cat("Result of multiplication","n")
print(result)
# Divide the matrices
result <- matrix1 / matrix2
cat("Result of division","n")
print(result)
Arrays
While matrices are confined to two dimensions, arrays
can be of any number of dimensions. The array
function takes a dim attribute which creates the
required number of dimension. In the below example
we create an array with two elements which are 3x3
matrices each.
When we execute the above code, it produces the
following result:
# Create an array.
a <- array(c('green','yellow'),dim = c(3,3,2))
print(a)
Factors
Factors are the r-objects which are created using a vector. It stores the vector along with the distinct values
of the elements in the vector as labels. The labels are always character irrespective of whether it is numeric
or character or Boolean etc. in the input vector. They are useful in statistical modeling.
Factors are created using the factor() function. The nlevels functions gives the count of levels.
# Create a vector.
apple_colors <-
c('green','green','yellow','red','red','red','green')
# Create a factor object.
factor_apple <- factor(apple_colors)
# Print the factor.
print(factor_apple)
print(nlevels(factor_apple))
[1] green green yellow red red red green
Levels: green red yellow
[1] 3
When we execute the above code, it produces the following result:
Data Frames
Data frames are tabular data objects. Unlike a matrix in data frame each column can contain different
modes of data. The first column can be numeric while the second column can be character and third
column can be logical. It is a list of vectors of equal length.
Data Frames are created using the data.frame() function.
When we execute the above code, it produces the following result −
# Create the data frame.
BMI <- data.frame( gender = c("Male", "Male","Female"), height = c(152, 171.5, 165),
weight = c(81,93, 78), Age = c(42,38,26) )
print(BMI)
Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. R
language is rich in built-in operators and provides following types of operators.
Types of Operators
We have the following types of operators in R programming −
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Miscellaneous Operators
Unit 1 - R Programming (Part 2).pptx
Unit 1 - R Programming (Part 2).pptx
Unit 1 - R Programming (Part 2).pptx
Unit 1 - R Programming (Part 2).pptx
Relational Operators:
Following table shows the relational operators supported by R language. Each element of the first vector is
compared with the corresponding element of the second vector. The result of comparison is a Boolean value.
Unit 1 - R Programming (Part 2).pptx
Unit 1 - R Programming (Part 2).pptx
Logical Operators:
It is applicable only to vectors of type logical, numeric or complex. All numbers greater than 1 are considered as
logical value 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.
Unit 1 - R Programming (Part 2).pptx
Miscellaneous Operators:
These operators are used to for specific purpose and not general mathematical or logical computation.
Control Statements
Control Statements or Decision making structures require the
programmer to specify one or more conditions to be evaluated or
tested by the program, along with a statement or statements to be
executed if the condition is determined to be true, and optionally, other
statements to be executed if the condition is determined to be false.
Following is the general form of a typical decision making structure
found in most of the programming languages −
Unit 1 - R Programming (Part 2).pptx
If Statement:
x <- 30L
if(is.integer(x))
{
print("X is an Integer")
}
Example
When the above code is compiled and executed, it produces the
following result −
[1] "X is an Integer"
If … Else .. Statement:
x <- c("what","is","truth")
if("Truth" %in% x) {
print("Truth is found")
} else {
print("Truth is not found")
}
Example
When the above code is compiled and executed, it produces the following
result −
[1] "Truth is not found"
x <- c("what","is","truth")
if("Truth" %in% x) {
print("Truth is found the first time")
} else if ("truth" %in% x) {
print("truth is found the second time")
} else {
print("No truth found")
}
When the above code is compiled and executed, it produces the following result −
[1] "truth is found the second time"
Switch Statement:
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a
case, and the variable being switched on is checked for each case.
x <- switch(
3,
"first",
"second",
"third",
"fourth"
)
print(x)
When the above code is compiled and executed, it produces the
following result −
[1] "third"
Loop Statements
There may be a situation when you need to execute a block of
code several number of times. In general, statements are executed
sequentially. The first statement in a function is executed first,
followed by the second, and so on.
Programming languages provide various control structures that
allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of
statements multiple times and the following is the general form of a
loop statement in most of the programming languages −
Unit 1 - R Programming (Part 2).pptx
Repeat Loop:
The Repeat loop executes the same code again and again until a stop condition is met.
v <- c("Hello","loop")
cnt <- 2
repeat {
print(v)
cnt <- cnt+1
if(cnt > 5) {
break
}
}
When the above code is compiled and executed, it
produces the following result −
[1] "Hello" "loop"
[1] "Hello" "loop"
[1] "Hello" "loop"
[1] "Hello" "loop"
While Loop:
The While loop executes the same code again and again until a stop
condition is met.
Here key point of the while loop is that the loop might not ever run. When
the condition is tested and the result is false, the loop body will be
skipped and the first statement after the while loop will be executed.
v <- c("Hello","while loop")
cnt <- 2
while (cnt < 7) {
print(v)
cnt = cnt + 1
}
When the above code is compiled and executed, it produces the
following result −
[1] "Hello" "while loop"
[1] "Hello" "while loop"
[1] "Hello" "while loop"
[1] "Hello" "while loop"
[1] "Hello" "while loop"
For Loop:
A For loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a
specific number of times.
v <- LETTERS[1:4]
for ( i in v) {
print(i)
}
When the above code is compiled and executed, it
produces the following result −
[1] "A"
[1] "B"
[1] "C"
[1] "D"
Functions
A function is a set of statements organized together to perform a specific task. R has a large number of in-built
functions and the user can create their own functions.
In R, a function is an object so the R interpreter is able to pass control to the function, along with arguments
that may be necessary for the function to accomplish the actions.
The function in turn performs its task and returns control to the interpreter as well as any result which may be
stored in other objects.
Function Components
The different parts of a function are −
1. Function Name − This is the actual name of the function. It is stored in R environment as an object with
this name.
2. Arguments − An argument is a placeholder. When a function is invoked, you pass a value to the
argument. Arguments are optional; that is, a function may contain no arguments. Also arguments can
have default values.
3. Function Body − The function body contains a collection of statements that defines what the function
does.
4. Return Value − The return value of a function is the last expression in the function body to be
evaluated.
R has many in-built functions which can be directly called in the program without defining them first. We can
also create and use our own functions referred as user defined functions.
Built-in Function:
Simple examples of in-built functions are seq(), mean(), max(), sum(x) and paste(...) etc.
They are directly called by user written programs.
# Create a sequence of numbers from 32 to 44.
print(seq(32,44))
# Find mean of numbers from 25 to 82.
print(mean(25:82))
# Find sum of numbers frm 41 to 68.
print(sum(41:68))
When we execute the above code, it produces the
following result −
[1] 32 33 34 35 36 37 38 39 40 41 42 43 44
[1] 53.5
[1] 1526
Calling a Function
# Create a function to print squares of numbers in sequence.
new.function <- function(a) {
for(i in 1:a) {
b <- i^2
print(b)
}
}
# Call the function new.function supplying 6 as an argument.
new.function(6)
When we execute the above code, it
produces the following result −
[1] 1
[1] 4
[1] 9
[1] 16
[1] 25
[1] 36
Unit 1 - R Programming (Part 2).pptx
Unit 1 - R Programming (Part 2).pptx
Unit 1 - R Programming (Part 2).pptx
String:
Any value written within a pair of single quote or double quotes in R is treated as a string.
Internally R stores every string within double quotes, even when you create them with single
quote.
Concatenating Strings - paste() function
Many strings in R are combined using the paste() function. It can take any number of arguments to be
combined together.
Changing the case - toupper() & tolower() functions
These functions change the case of characters of a string.
Extracting parts of a string - substring() function
This function extracts parts of a String.
Some R functions for computing Descriptive
Statistics
Description R function
Mean mean()
Standard deviation sd()
Variance var()
Minimum min()
Maximum maximum()
Median median()
Range of values (minimum and
maximum)
range()
Sample quantiles quantile()
Generic function summary()
Interquartile range IQR()
Descriptive Statistics
Summary: the function summary() is automatically applied to each column. The format of the result
depends on the type of the data contained in the column. For example:
If the column is a numeric variable, mean, median, min, max and quartiles are returned. If the column is a
factor variable, the number of observations in each group is returned.
# Create the data frame.
emp.data <- data.frame (emp_id = c(1:3), emp_name = c("Ramu","Venkat","Maha"), salary = c(623.3,515.2,611.0))
g = summary(emp.data, digit=1)
print(g)
When we execute the above code, it produces the following result −
Descriptive Statistics
Summary of a single variable. Five values are returned: the mean, median, Q1 and Q3
quartiles, min and max in one single line call.
f=summary(emp.data$salary)
print(f)
When we execute the above code, it produces the following result −
# Compute the mode---
install.packages("modeest")
# Import the library
library(modeest)
v = c(10,20,30,40,20)
# compute the Mode Value
c = mfv (v)
print(c)
Dr. Rambabu Palaka
Professor
School of Engineering
Malla Reddy University, Hyderabad
Mobile: +91-9652665840
Email: drrambabu@mallareddyuniversity.ac.in
Reference:
R Tutorial - Website

More Related Content

What's hot (20)

PPTX
2. R-basics, Vectors, Arrays, Matrices, Factors
krishna singh
 
PDF
Data preprocessing using Machine Learning
Gopal Sakarkar
 
PPTX
Linear regression with gradient descent
Suraj Parmar
 
PPTX
Data analysis with R
ShareThis
 
PPTX
Logistic regression
YashwantGahlot1
 
PPTX
How to get started with R programming
Ramon Salazar
 
PPTX
Getting Started with R
Sankhya_Analytics
 
PPTX
Relational algebra ppt
GirdharRatne
 
PPTX
R programming presentation
Akshat Sharma
 
PDF
List,tuple,dictionary
nitamhaske
 
PPTX
Data preprocessing in Machine learning
pyingkodi maran
 
PDF
Missing data handling
QuantUniversity
 
PPTX
Python Functions
Mohammed Sikander
 
PDF
Symbol table in compiler Design
Kuppusamy P
 
PPTX
Data Analysis with Python Pandas
Neeru Mittal
 
PDF
Pandas
maikroeder
 
PDF
R Programming: Introduction To R Packages
Rsquared Academy
 
PPT
1.7 data reduction
Krish_ver2
 
PDF
Introduction to R
Kazuki Yoshida
 
PDF
Introduction to R and R Studio
Rupak Roy
 
2. R-basics, Vectors, Arrays, Matrices, Factors
krishna singh
 
Data preprocessing using Machine Learning
Gopal Sakarkar
 
Linear regression with gradient descent
Suraj Parmar
 
Data analysis with R
ShareThis
 
Logistic regression
YashwantGahlot1
 
How to get started with R programming
Ramon Salazar
 
Getting Started with R
Sankhya_Analytics
 
Relational algebra ppt
GirdharRatne
 
R programming presentation
Akshat Sharma
 
List,tuple,dictionary
nitamhaske
 
Data preprocessing in Machine learning
pyingkodi maran
 
Missing data handling
QuantUniversity
 
Python Functions
Mohammed Sikander
 
Symbol table in compiler Design
Kuppusamy P
 
Data Analysis with Python Pandas
Neeru Mittal
 
Pandas
maikroeder
 
R Programming: Introduction To R Packages
Rsquared Academy
 
1.7 data reduction
Krish_ver2
 
Introduction to R
Kazuki Yoshida
 
Introduction to R and R Studio
Rupak Roy
 

Similar to Unit 1 - R Programming (Part 2).pptx (20)

PPTX
Unit-5 BDS.pptx on basics of data science
SyedFahad39584
 
PDF
R basics
Sagun Baijal
 
PDF
R-Language-Lab-Manual-lab-1.pdf
DrGSakthiGovindaraju
 
PDF
R-Language-Lab-Manual-lab-1.pdf
KabilaArun
 
PDF
R-Language-Lab-Manual-lab-1.pdf
attalurilalitha
 
PDF
R data types
Learnbay Datascience
 
PPTX
R language tutorial.pptx
GABBARSINGH699271
 
PPTX
Data Types of R.pptx
Ramakrishna Reddy Bijjam
 
PPT
R_Language_study_forstudents_R_Material.ppt
Suresh Babu
 
PPT
Brief introduction to R Lecturenotes1_R .ppt
geethar79
 
PPTX
Get started with R lang
senthil0809
 
PPT
Lecture1_R.ppt
ArchishaKhandareSS20
 
PPT
Modeling in R Programming Language for Beginers.ppt
anshikagoel52
 
PPT
Lecture1 r
Sandeep242951
 
PPT
Lecture1_R.ppt
vikassingh569137
 
PPT
Lecture1_R Programming Introduction1.ppt
premak23
 
PPT
Inroduction to r
manikanta361
 
PDF
Basics of R programming for analytics [Autosaved] (1).pdf
suanshu15
 
PPTX
Unit 3
Piyush Rochwani
 
PPTX
R basics for MBA Students[1].pptx
rajalakshmi5921
 
Unit-5 BDS.pptx on basics of data science
SyedFahad39584
 
R basics
Sagun Baijal
 
R-Language-Lab-Manual-lab-1.pdf
DrGSakthiGovindaraju
 
R-Language-Lab-Manual-lab-1.pdf
KabilaArun
 
R-Language-Lab-Manual-lab-1.pdf
attalurilalitha
 
R data types
Learnbay Datascience
 
R language tutorial.pptx
GABBARSINGH699271
 
Data Types of R.pptx
Ramakrishna Reddy Bijjam
 
R_Language_study_forstudents_R_Material.ppt
Suresh Babu
 
Brief introduction to R Lecturenotes1_R .ppt
geethar79
 
Get started with R lang
senthil0809
 
Lecture1_R.ppt
ArchishaKhandareSS20
 
Modeling in R Programming Language for Beginers.ppt
anshikagoel52
 
Lecture1 r
Sandeep242951
 
Lecture1_R.ppt
vikassingh569137
 
Lecture1_R Programming Introduction1.ppt
premak23
 
Inroduction to r
manikanta361
 
Basics of R programming for analytics [Autosaved] (1).pdf
suanshu15
 
R basics for MBA Students[1].pptx
rajalakshmi5921
 
Ad

More from Malla Reddy University (20)

PPTX
Angular Directives
Malla Reddy University
 
PPTX
Unit 2 - Data Manipulation with R.pptx
Malla Reddy University
 
PPTX
Unit 1 - Statistics (Part 1).pptx
Malla Reddy University
 
PPTX
Unit 2 - Data Binding.pptx
Malla Reddy University
 
PPTX
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Malla Reddy University
 
PPTX
GIS - Project Planning and Implementation
Malla Reddy University
 
PPTX
Geo-spatial Analysis and Modelling
Malla Reddy University
 
PPTX
GIS - Topology
Malla Reddy University
 
PPTX
Geographical Information System (GIS)
Malla Reddy University
 
PPTX
Introduction to Maps
Malla Reddy University
 
PPTX
Fluid Mechanics - Fluid Dynamics
Malla Reddy University
 
PPTX
Fluid Kinematics
Malla Reddy University
 
PPTX
Fluid Mechanics - Hydrostatic Pressure
Malla Reddy University
 
PPTX
Fluid Mechanics - Fluid Pressure and its measurement
Malla Reddy University
 
PPTX
Fluid Mechanics - Fluid Properties
Malla Reddy University
 
PPTX
Reciprocating Pump
Malla Reddy University
 
PPTX
E-waste Management
Malla Reddy University
 
PPTX
Biomedical Waste Management
Malla Reddy University
 
PPTX
Hazardous Waste Management
Malla Reddy University
 
PPTX
Digital Elevation Model (DEM)
Malla Reddy University
 
Angular Directives
Malla Reddy University
 
Unit 2 - Data Manipulation with R.pptx
Malla Reddy University
 
Unit 1 - Statistics (Part 1).pptx
Malla Reddy University
 
Unit 2 - Data Binding.pptx
Malla Reddy University
 
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Malla Reddy University
 
GIS - Project Planning and Implementation
Malla Reddy University
 
Geo-spatial Analysis and Modelling
Malla Reddy University
 
GIS - Topology
Malla Reddy University
 
Geographical Information System (GIS)
Malla Reddy University
 
Introduction to Maps
Malla Reddy University
 
Fluid Mechanics - Fluid Dynamics
Malla Reddy University
 
Fluid Kinematics
Malla Reddy University
 
Fluid Mechanics - Hydrostatic Pressure
Malla Reddy University
 
Fluid Mechanics - Fluid Pressure and its measurement
Malla Reddy University
 
Fluid Mechanics - Fluid Properties
Malla Reddy University
 
Reciprocating Pump
Malla Reddy University
 
E-waste Management
Malla Reddy University
 
Biomedical Waste Management
Malla Reddy University
 
Hazardous Waste Management
Malla Reddy University
 
Digital Elevation Model (DEM)
Malla Reddy University
 
Ad

Recently uploaded (20)

PDF
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
PPTX
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
PDF
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PPTX
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PPTX
How to Set Maximum Difference Odoo 18 POS
Celine George
 
PDF
LAW OF CONTRACT ( 5 YEAR LLB & UNITARY LLB)- MODULE-3 - LEARN THROUGH PICTURE
APARNA T SHAIL KUMAR
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PDF
CEREBRAL PALSY: NURSING MANAGEMENT .pdf
PRADEEP ABOTHU
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PDF
The Different Types of Non-Experimental Research
Thelma Villaflores
 
PPTX
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
PPTX
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PPTX
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
PDF
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 
PDF
community health nursing question paper 2.pdf
Prince kumar
 
PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
How to Set Maximum Difference Odoo 18 POS
Celine George
 
LAW OF CONTRACT ( 5 YEAR LLB & UNITARY LLB)- MODULE-3 - LEARN THROUGH PICTURE
APARNA T SHAIL KUMAR
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
CEREBRAL PALSY: NURSING MANAGEMENT .pdf
PRADEEP ABOTHU
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
The Different Types of Non-Experimental Research
Thelma Villaflores
 
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 
community health nursing question paper 2.pdf
Prince kumar
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 

Unit 1 - R Programming (Part 2).pptx

  • 1. INTRODUCTION TO R (DATA VISUALIZATION) Dr. P. Rambabu, M. Tech., Ph.D., F.I.E. 19-Feb-2022
  • 2. Topics 1. Overview and about R 2. R Studio Installation 3. Fundamentals of R Programming a) Data Structures and Data Types b) Operators c) Control Statements d) Loop Statements e) Functions 4. Descriptive Analysis using R a) Maximum, Minimum, Range b) Mean, Median and Mode c) Variance, Standard Deviation d) Quantiles, IQR e) Summary
  • 3. Introduction to R “R” is a programming language and software environment for Statistical analysis, Graphics Representation and Reporting. R was first implemented in the early 1990's by Ross Ihaka and Robert Gentleman at the University of Auckland, New Zealand, and it is currently developed by the R Development Core Team. R is freely available under the GNU General Public License, and pre-compiled binary versions are provided for various operating systems like Linux, Windows and Mac.
  • 4. Installation of R Step 1: Go to CRAN R project website. Step 2: Click on the Download R for Windows link. Step 3: Click on the base subdirectory link or install R for the first time link. Step 4: Click Download R X.X.X for Windows and save the executable .exe file. Step 5: Run the .exe file and follow the installation instructions. a) Select the desired language and then click Next. b) Read the license agreement and click Next. c) Select the components to install (it is recommended to install all the components). Click Next. d) Enter/browse the folder/path you wish to install R into and then confirm by clicking Next. e) Select additional tasks like creating desktop shortcuts etc. then click Next. f) Wait for the installation process to complete. g) Click on Finish to complete the installation.
  • 5. Installation of RStudio Install RStudio on Windows Step 1: With R-base installed, let’s move on to installing RStudio. To begin, go to download RStudio and click on the download button for RStudio desktop. Step 2: Click on the link for the windows version of RStudio and save the .exe file. Step 3: Run the .exe and follow the installation instructions. a) Click Next on the welcome window. b) Enter/browse the path to the installation folder and click Next to proceed. c) Select the folder for the start menu shortcut or click on do not create shortcuts and then click Next. d) Wait for the installation process to complete. e) Click Finish to end the installation.
  • 6. "Hello, World!" Program Depending on the needs, you can program either at R command prompt or you can use an R script file to write your program. # My first program in R Programming (using R Script File) myString <- "Hello, World!" print(myString) Output: [1] "Hello, World!“ R does not support multi-line comments but you can perform a trick which is something as follows: if (FALSE) { "This is a demo for multi-line comments and it should be put inside either a single OR double quote” }
  • 8. Variable Assignment: The variables can be assigned values using leftward, rightward and equal to operator. The values of the variables can be printed using print() or cat() function. The cat() function combines multiple items into a continuous print output. # Assignment using equal operator. var.1 = c(0,1,2,3) # Assignment using leftward operator. var.2 <- c("learn","R") # Assignment using rightward operator. c(TRUE,1) -> var.3 print(var.1) cat ("var.1 is ", var.1 ,"n") cat ("var.2 is ", var.2 ,"n") cat ("var.3 is ", var.3 ,"n") When we execute the above code, it produces the following result − Note − The vector c(TRUE,1) has a mix of logical and numeric class. So logical class is coerced to numeric class making TRUE as 1.
  • 9. Data Type of a Variable: In R, a variable itself is not declared of any data type, rather it gets the data type of the R - object assigned to it. So R is called a dynamically typed language, which means that we can change a variable’s data type of the same variable again and again when using it in a program. var_x <- "Hello" cat("The class of var_x is ",class(var_x),"n") var_x <- 34.5 cat(" Now the class of var_x is ",class(var_x),"n") var_x <- 27L cat(" Next the class of var_x becomes ",class(var_x),"n") When we execute the above code, it produces the following result − The class of var_x is character Now the class of var_x is numeric Next the class of var_x becomes integer
  • 10. Data Structures In contrast to other programming languages like C and java in R, the variables are not declared as some data type. The variables are assigned with R-Objects and the data type of the R-object becomes the data type of the variable. There are many types of R-objects. The frequently used ones are − • Vectors • Lists • Matrices • Arrays • Factors • Data Frames
  • 11. The simplest of these objects is the vector object and there are six data types of these atomic vectors, also termed as six classes of vectors. The other R-Objects are built upon the atomic vectors. Data Type Example 1. Logical True, False 2. Numerical 12.3, 5, 99 3. Integer 2L, 34L, 0L 4. Complex 3 + 2i 5. Character 'a' , '"good", "TRUE", '23.4' 6. Raw "Hello" is stored as 48 65 6c 6c 6f
  • 14. Vectors In R programming, the very basic data types are the R-objects called vectors which hold elements of different classes (Data Types). Vectors: When you want to create vector with more than one element, you should use c() function which means to combine the elements into a vector.
  • 15. Vector Manipulation Vector Arithmetic Two vectors of same length can be added, subtracted, multiplied or divided giving the result as a vector output. # Create two vectors. v1 <- c(3,8,4,5,0,11) v2 <- c(4,11,0,8,1,2) # Vector addition. add.result <- v1+v2 print(add.result) # Vector subtraction. sub.result <- v1-v2 print(sub.result) # Vector multiplication. multi.result <- v1*v2 print(multi.result) # Vector division. divi.result <- v1/v2 print(divi.result) When we execute the above code, it produces the following result − [1] 7 19 4 13 1 13 [1] -1 -3 4 -3 -1 9 [1] 12 88 0 40 0 22 [1] 0.7500000 0.7272727 Inf 0.6250000 0.0000000 5.5000000
  • 16. Vector Manipulation Vector Element Sorting Elements in a vector can be sorted using the sort() function. When we execute the above code, it produces the following result − v <- c(3,8,4,5,0,11, -9, 304) # Sort the elements of the vector. sort.result <- sort(v) print(sort.result) # Sort the elements in the reverse order. revsort.result <- sort(v, decreasing = TRUE) print(revsort.result) # Sorting character vectors. v <- c("Red","Blue","yellow","violet") sort.result <- sort(v) print(sort.result) # Sorting character vectors in reverse order. revsort.result <- sort(v, decreasing = TRUE) print(revsort.result) [1] -9 0 3 4 5 8 11 304 [1] 304 11 8 5 4 3 0 -9 [1] "Blue" "Red" "violet" "yellow" [1] "yellow" "violet" "Red" "Blue"
  • 17. Lists A list is an R-object which can contain many different types of elements inside it like vectors, functions and even another list inside it. When we execute the above code, it produces the following result − # Create a list. list1 <- list(c(2,5,3),21.3,sin) # Print the list. print(list1) [[1]] [1] 2 5 3 [[2]] [1] 21.3 [[3]] function (x) .Primitive("sin")
  • 18. Naming List Elements The list elements can be given names and they can be accessed using these names. # Create a list containing a vector, a matrix and a list. list_data <- list(c("Jan","Feb","Mar"), matrix(c(3,9,5,1,-2,8), nrow = 2), list("green",12.3)) # Give names to the elements in the list. names(list_data) <- c("1st Quarter", "A_Matrix", "A Inner list") # Show the list. print(list_data) When we execute the above code, it produces the following result −
  • 19. Manipulating Lists We can add, delete and update list elements as shown below. We can add and delete elements only at the end of a list. But we can update any element. When we execute the above code, it produces the following result − # Create a list containing a vector, a matrix and a list. list_data <- list(c("Jan","Feb","Mar"), matrix(c(3,9,5,1,-2,8), nrow = 2), list("green",12.3)) # Give names to the elements in the list. names(list_data) <- c("1st Quarter", "A_Matrix", "A Inner list") # Add element at the end of the list. list_data[4] <- "New element" print(list_data[4]) # Remove the last element. list_data[4] <- NULL # Print the 4th Element. print(list_data[4]) # Update the 3rd Element. list_data[3] <- "updated element" print(list_data[3])
  • 20. Converting List to Vector A list can be converted to a vector so that the elements of the vector can be used for further manipulation. All the arithmetic operations on vectors can be applied after the list is converted into vectors. To do this conversion, we use the unlist() function. It takes the list as input and produces a vector. When we execute the above code, it produces the following result − # Create lists. list1 <- list(1:5) print(list1) list2 <-list(10:14) print(list2) # Convert the lists to vectors. v1 <- unlist(list1) v2 <- unlist(list2) print(v1) print(v2) # Now add the vectors result <- v1+v2 print(result)
  • 21. Merging Lists You can merge many lists into one list by placing all the lists inside one list() function. When we execute the above code, it produces the following result − # Create two lists. list1 <- list(1,2,3) list2 <- list("Sun","Mon","Tue") # Merge the two lists. merged.list <- c(list1,list2) # Print the merged list. print(merged.list)
  • 22. Matrices A matrix is a two-dimensional rectangular data set. It can be created using a vector input to the matrix function. When we execute the above code, it produces the following result − # Create a matrix. M = matrix( c('a','a','b','c','b','a'), nrow = 2, ncol = 3, byrow = TRUE) print(M)
  • 23. Accessing Elements of Matrix Elements of a matrix can be accessed by using the column and row index of the element. We consider the matrix P above to find the specific elements below When we execute the above code, it produces the following result − # Define the column and row names. rownames = c("row1", "row2", "row3", "row4") colnames = c("col1", "col2", "col3") # Create the matrix. P <- matrix(c(3:14), nrow = 4, byrow = TRUE, dimnames = list(rownames, colnames)) # Access the element at 3rd column and 1st row. print(P[1,3]) # Access the element at 2nd column and 4th row. print(P[4,2]) # Access only the 2nd row. print(P[2,]) # Access only the 3rd column. print(P[,3])
  • 24. Matrix Computations Various mathematical operations are performed on the matrices using the R operators. The result of the operation is also a matrix. The dimensions (number of rows and columns) should be same for the matrices involved in the operation. Matrix Addition & Subtraction When we execute the above code, it produces the following result − # Create two 2x3 matrices. matrix1 <- matrix(c(3, 9, -1, 4, 2, 6), nrow = 2) print(matrix1) matrix2 <- matrix(c(5, 2, 0, 9, 3, 4), nrow = 2) print(matrix2) # Add the matrices. result <- matrix1 + matrix2 cat("Result of addition","n") print(result) # Subtract the matrices result <- matrix1 - matrix2 cat("Result of subtraction","n") print(result)
  • 25. Matrix Computations Matrix Multiplication & Division When we execute the above code, it produces the following result − # Create two 2x3 matrices. matrix1 <- matrix(c(3, 9, -1, 4, 2, 6), nrow = 2) print(matrix1) matrix2 <- matrix(c(5, 2, 0, 9, 3, 4), nrow = 2) print(matrix2) # Multiply the matrices. result <- matrix1 * matrix2 cat("Result of multiplication","n") print(result) # Divide the matrices result <- matrix1 / matrix2 cat("Result of division","n") print(result)
  • 26. Arrays While matrices are confined to two dimensions, arrays can be of any number of dimensions. The array function takes a dim attribute which creates the required number of dimension. In the below example we create an array with two elements which are 3x3 matrices each. When we execute the above code, it produces the following result: # Create an array. a <- array(c('green','yellow'),dim = c(3,3,2)) print(a)
  • 27. Factors Factors are the r-objects which are created using a vector. It stores the vector along with the distinct values of the elements in the vector as labels. The labels are always character irrespective of whether it is numeric or character or Boolean etc. in the input vector. They are useful in statistical modeling. Factors are created using the factor() function. The nlevels functions gives the count of levels. # Create a vector. apple_colors <- c('green','green','yellow','red','red','red','green') # Create a factor object. factor_apple <- factor(apple_colors) # Print the factor. print(factor_apple) print(nlevels(factor_apple)) [1] green green yellow red red red green Levels: green red yellow [1] 3 When we execute the above code, it produces the following result:
  • 28. Data Frames Data frames are tabular data objects. Unlike a matrix in data frame each column can contain different modes of data. The first column can be numeric while the second column can be character and third column can be logical. It is a list of vectors of equal length. Data Frames are created using the data.frame() function. When we execute the above code, it produces the following result − # Create the data frame. BMI <- data.frame( gender = c("Male", "Male","Female"), height = c(152, 171.5, 165), weight = c(81,93, 78), Age = c(42,38,26) ) print(BMI)
  • 29. Operators An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. R language is rich in built-in operators and provides following types of operators. Types of Operators We have the following types of operators in R programming − 1. Arithmetic Operators 2. Relational Operators 3. Logical Operators 4. Assignment Operators 5. Miscellaneous Operators
  • 34. Relational Operators: Following table shows the relational operators supported by R language. Each element of the first vector is compared with the corresponding element of the second vector. The result of comparison is a Boolean value.
  • 37. Logical Operators: It is applicable only to vectors of type logical, numeric or complex. All numbers greater than 1 are considered as logical value 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.
  • 39. Miscellaneous Operators: These operators are used to for specific purpose and not general mathematical or logical computation.
  • 40. Control Statements Control Statements or Decision making structures require the programmer to specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Following is the general form of a typical decision making structure found in most of the programming languages −
  • 43. x <- 30L if(is.integer(x)) { print("X is an Integer") } Example When the above code is compiled and executed, it produces the following result − [1] "X is an Integer"
  • 44. If … Else .. Statement:
  • 45. x <- c("what","is","truth") if("Truth" %in% x) { print("Truth is found") } else { print("Truth is not found") } Example When the above code is compiled and executed, it produces the following result − [1] "Truth is not found"
  • 46. x <- c("what","is","truth") if("Truth" %in% x) { print("Truth is found the first time") } else if ("truth" %in% x) { print("truth is found the second time") } else { print("No truth found") } When the above code is compiled and executed, it produces the following result − [1] "truth is found the second time"
  • 47. Switch Statement: A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case. x <- switch( 3, "first", "second", "third", "fourth" ) print(x) When the above code is compiled and executed, it produces the following result − [1] "third"
  • 48. Loop Statements There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially. The first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times and the following is the general form of a loop statement in most of the programming languages −
  • 50. Repeat Loop: The Repeat loop executes the same code again and again until a stop condition is met. v <- c("Hello","loop") cnt <- 2 repeat { print(v) cnt <- cnt+1 if(cnt > 5) { break } } When the above code is compiled and executed, it produces the following result − [1] "Hello" "loop" [1] "Hello" "loop" [1] "Hello" "loop" [1] "Hello" "loop"
  • 51. While Loop: The While loop executes the same code again and again until a stop condition is met. Here key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed. v <- c("Hello","while loop") cnt <- 2 while (cnt < 7) { print(v) cnt = cnt + 1 } When the above code is compiled and executed, it produces the following result − [1] "Hello" "while loop" [1] "Hello" "while loop" [1] "Hello" "while loop" [1] "Hello" "while loop" [1] "Hello" "while loop"
  • 52. For Loop: A For loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. v <- LETTERS[1:4] for ( i in v) { print(i) } When the above code is compiled and executed, it produces the following result − [1] "A" [1] "B" [1] "C" [1] "D"
  • 53. Functions A function is a set of statements organized together to perform a specific task. R has a large number of in-built functions and the user can create their own functions. In R, a function is an object so the R interpreter is able to pass control to the function, along with arguments that may be necessary for the function to accomplish the actions. The function in turn performs its task and returns control to the interpreter as well as any result which may be stored in other objects.
  • 54. Function Components The different parts of a function are − 1. Function Name − This is the actual name of the function. It is stored in R environment as an object with this name. 2. Arguments − An argument is a placeholder. When a function is invoked, you pass a value to the argument. Arguments are optional; that is, a function may contain no arguments. Also arguments can have default values. 3. Function Body − The function body contains a collection of statements that defines what the function does. 4. Return Value − The return value of a function is the last expression in the function body to be evaluated. R has many in-built functions which can be directly called in the program without defining them first. We can also create and use our own functions referred as user defined functions.
  • 55. Built-in Function: Simple examples of in-built functions are seq(), mean(), max(), sum(x) and paste(...) etc. They are directly called by user written programs. # Create a sequence of numbers from 32 to 44. print(seq(32,44)) # Find mean of numbers from 25 to 82. print(mean(25:82)) # Find sum of numbers frm 41 to 68. print(sum(41:68)) When we execute the above code, it produces the following result − [1] 32 33 34 35 36 37 38 39 40 41 42 43 44 [1] 53.5 [1] 1526
  • 56. Calling a Function # Create a function to print squares of numbers in sequence. new.function <- function(a) { for(i in 1:a) { b <- i^2 print(b) } } # Call the function new.function supplying 6 as an argument. new.function(6) When we execute the above code, it produces the following result − [1] 1 [1] 4 [1] 9 [1] 16 [1] 25 [1] 36
  • 60. String: Any value written within a pair of single quote or double quotes in R is treated as a string. Internally R stores every string within double quotes, even when you create them with single quote.
  • 61. Concatenating Strings - paste() function Many strings in R are combined using the paste() function. It can take any number of arguments to be combined together.
  • 62. Changing the case - toupper() & tolower() functions These functions change the case of characters of a string.
  • 63. Extracting parts of a string - substring() function This function extracts parts of a String.
  • 64. Some R functions for computing Descriptive Statistics Description R function Mean mean() Standard deviation sd() Variance var() Minimum min() Maximum maximum() Median median() Range of values (minimum and maximum) range() Sample quantiles quantile() Generic function summary() Interquartile range IQR()
  • 65. Descriptive Statistics Summary: the function summary() is automatically applied to each column. The format of the result depends on the type of the data contained in the column. For example: If the column is a numeric variable, mean, median, min, max and quartiles are returned. If the column is a factor variable, the number of observations in each group is returned. # Create the data frame. emp.data <- data.frame (emp_id = c(1:3), emp_name = c("Ramu","Venkat","Maha"), salary = c(623.3,515.2,611.0)) g = summary(emp.data, digit=1) print(g) When we execute the above code, it produces the following result −
  • 66. Descriptive Statistics Summary of a single variable. Five values are returned: the mean, median, Q1 and Q3 quartiles, min and max in one single line call. f=summary(emp.data$salary) print(f) When we execute the above code, it produces the following result − # Compute the mode--- install.packages("modeest") # Import the library library(modeest) v = c(10,20,30,40,20) # compute the Mode Value c = mfv (v) print(c)
  • 67. Dr. Rambabu Palaka Professor School of Engineering Malla Reddy University, Hyderabad Mobile: +91-9652665840 Email: [email protected] Reference: R Tutorial - Website