UNIT - II
Introduction
R is a Programming Language that is mostly used for machine learning, data analysis, and
statistical computing. It is an interpreted language and is platform independent that means it
can be used on platforms like Windows, Linux, and macOS.
Key Features and Applications
Some key features of R that make the R one of the most demanding job in data science
market are:
• Basic Statistics: The most common basic statistics terms are the mean, mode, and
median. These are all known as “Measures of Central Tendency.” So using the R
language we can measure central tendency very easily.
• Static graphics: R is rich with facilities for creating and developing various kinds of
static graphics including graphic maps, mosaic plots, biplots, and the list goes on.
• Probability distributions: Using R we can easily handle various types of probability
distribution such as Binomial Distribution, Normal Distribution, Chi-squared
Distribution, and many more.
• R Packages: One of the major features of R is it has a wide availability of libraries. R
has CRAN(Comprehensive R Archive Network), which is a repository holding more
than 10,0000 packages.
• Distributed Computing: Distributed computing is a model in which components of a
software system are shared among multiple computers to improve efficiency and
performance. Two new packages ddR and multidplyr used for distributed
programming in R were released in November 2015.
Applications
• We use R for Data Science. It gives us a broad variety of libraries related to statistics.
It also provides the environment for statistical computing and design.
• R is used by many quantitative analysts as its programming tool. Thus, it helps in data
importing and cleaning.
• R is the most prevalent language. So many data analysts and research programmers
use it. Hence, it is used as a fundamental tool for finance.
• Tech giants like Google, Facebook, Bing, Twitter, Accenture, Wipro, and many more
using R nowadays.
Variables:
R is a dynamically typed language, i.e. the variables are not declared with a data type rather
they take the data type of the R-object assigned to them. In R, the assignment can be denoted
in three ways.
• Using equal operator- data is copied from right to left.
variable_name = value
• Using leftward operator- data is copied from right to left.
variable_name <- value
• Using rightward operator- data is copied from left to right.
value -> variable_name
Example:
• R
var1 = "gfg"
print(var1)
var2 <- "gfg"
print(var2)
"gfg" -> var3
print(var3)
Output:
[1] "gfg"
[1] "gfg"
[1] "gfg"
Operators
Operators are the symbols directing the various kinds of operations that can be performed
between the operands. Operators simulate the various mathematical, logical and decision
operations performed on a set of Complex Numbers, Integers, and Numericals as input
operands. These are classified based on their functionality –
Arithmetic Operators: Arithmetic operations simulate various math operations, like
addition, subtraction, multiplication, division and modulo.
a <- 12
b <- 5
cat ("Addition :", a + b, "\n")
cat ("Subtraction :", a - b, "\n")
cat ("Multiplication :", a * b, "\n")
cat ("Division :", a / b, "\n")
cat ("Modulo :", a %% b, "\n")
cat ("Power operator :", a ^ b)
Output:
Addition : 17
Subtraction : 7
Multiplication : 60
Division : 2.4
Modulo : 2
Power operator : 248832
Logical Operators: Logical operations simulate element-wise decision operations, based on
the specified operator between the operands, which are then evaluated to either a True or
False boolean value.
vec1 <- c(FALSE, TRUE)
vec2 <- c(TRUE,FALSE)
cat ("Element wise AND :", vec1 & vec2, "\n")
cat ("Element wise OR :", vec1 | vec2, "\n")
cat ("Logical AND :", vec1 && vec2, "\n")
cat ("Logical OR :", vec1 || vec2, "\n")
cat ("Negation :", !vec1)
Output:
Element wise AND : FALSE
Element wise OR : TRUE
Logical AND : FALSE
Logical OR : TRUE
Negation : TRUE FALSE
Relational Operators: The relational operators carry out comparison operations between the
corresponding elements of the operands.
a <- 10
b <- 14
cat ("a less than b :", a < b, "\n")
cat ("a less than equal to b :", a <= b, "\n")
cat ("a greater than b :", a > b, "\n")
cat ("a greater than equal to b :", a >= b, "\n")
cat ("a not equal to b :", a != b, "\n")
Output:
a less than b : TRUE
a less than equal to b : TRUE
a greater than b : FALSE
a greater than equal to b : FALSE
a not equal to b : TRUE
Assignment Operators: Assignment operators are used to assign values to various data
objects in R.
v1 <- "GeeksForGeeks"
v2 <<- "GeeksForGeeks"
v3 = "GeeksForGeeks"
"GeeksForGeeks" ->> v4
"GeeksForGeeks" -> v5
cat("Value 1 :", v1, "\n")
cat("Value 2 :", v2, "\n")
cat("Value 3 :", v3, "\n")
cat("Value 4 :", v4, "\n")
cat("Value 5 :", v5)
Output:
Value 1 : GeeksForGeeks
Value 2 : GeeksForGeeks
Value 3 : GeeksForGeeks
Value 4 : GeeksForGeeks
Value 5 : GeeksForGeeks
Data Types
Each variable in R has an associated data type. Each data type requires different amounts of
memory and has some specific operations which can be performed over it. R supports 5 type
of data types. These are –
Data
Types Example Description
Decimal values are called numerics in R. It is the default
Numeric 1, 2, 12, 36
data type for numbers in R.
R supports integer data types which are the set of all
Integer 1L, 2L, 34L integers. Capital ‘L’ notation as a suffix is used to denote
that a particular value is of the integer data type.
TRUE,
Logical Take either a value of true or false
FALSE
Set of all the complex numbers. The complex data type is
Complex 2+3i, 5+7i
to store numbers with an imaginary component.
‘a’, ’12’,
R supports character data types where you have all the
Character “GFG”,
alphabets and special characters.
”’hello”’
Basics of Input/Output
Taking Input from the User:
R Language provides us with two inbuilt functions to read the input from the keyboard.
readline() method: It takes input in string format. If one inputs an integer then it is inputted
as a string.
var = readline();
scan() method: This method reads data in the form of a vector or list. This method is a very
handy method while inputs are needed to taken quickly for any mathematical calculation or
for any dataset.
x = scan()
Printing Output to Console:
R Provides various functions to write output to the screen, let’s see them –
print(): It is the most common method to print the output.
print("Hello")
x <- "Welcome to GeeksforGeeks"
print(x)
Output:
[1] "Hello"
[1] "Welcome to GeeksforGeeks"
cat(): cat() converts its arguments to character strings. This is useful for printing output in
user defined functions.
x = "Hello"
cat(x, "\nwelcome")
cat("\nto GeeksForGeeks")
Output:
Hello
welcome
to GeeksForGeeks
Data Structures in R Programming
A data structure is a particular way of organizing data in a computer so that it can be used
effectively. The idea is to reduce the space and time complexities of different tasks. Data
structures in R programming are tools for holding multiple values.
R’s base data structures are often organized by their dimensionality (1D, 2D, or nD) and
whether they’re homogeneous (all elements must be of the identical type) or heterogeneous
(the elements are often of various types). This gives rise to the six data types which are most
frequently utilized in data analysis.
Vectors
A vector is an ordered collection of basic data types of a given length. The only key thing
here is all the elements of a vector must be of the identical data type e.g homogeneous data
structures. Vectors are one-dimensional data structures.
Example:
X = c(1, 3, 5, 7, 8)
print(X)
Output:
[1] 1 3 5 7 8
Lists
A list is a generic object consisting of an ordered collection of objects. Lists are
heterogeneous data structures. These are also one-dimensional data structures. A list can be a
list of vectors, list of matrices, a list of characters and a list of functions and so on.
Example:
empId = c(1, 2, 3, 4)
empName = c("Debi", "Sandeep", "Subham", "Shiba")
numberOfEmp = 4
empList = list(empId, empName, numberOfEmp)
print(empList)
Output:
[[1]]
[1] 1 2 3 4
[[2]]
[1] "Debi" "Sandeep" "Subham" "Shiba"
[[3]]
[1] 4
Dataframes
Dataframes are generic data objects of R which are used to store the tabular data. Dataframes
are the foremost popular data objects in R programming because we are comfortable in
seeing the data within the tabular form. They are two-dimensional, heterogeneous data
structures. These are lists of vectors of equal lengths.
Data frames have the following constraints placed upon them:
• A data-frame must have column names and every row should have a unique name.
• Each column must have the identical number of items.
• Each item in a single column must be of the same data type.
• Different columns may have different data types.
To create a data frame we use the [Link]() function.
Example:
Name = c("Amiya", "Raj", "Asish")
Language = c("R", "Python", "Java")
Age = c(22, 25, 45)
df = [Link](Name, Language, Age)
print(df)
Output:
Name Language Age
1 Amiya R 22
2 Raj Python 25
3 Asish Java 45
Matrices
A matrix is a rectangular arrangement of numbers in rows and columns. In a matrix, as we
know rows are the ones that run horizontally and columns are the ones that run vertically.
Matrices are two-dimensional, homogeneous data structures.
Now, let’s see how to create a matrix in R. To create a matrix in R you need to use the
function called matrix. The arguments to this matrix() are the set of elements in the vector.
You have to pass how many numbers of rows and how many numbers of columns you want
to have in your matrix and this is the important point you have to remember that by default,
matrices are in column-wise order.
Example:
A = matrix(
c(1, 2, 3, 4, 5, 6, 7, 8, 9),
nrow = 3, ncol = 3,
byrow = TRUE
)
print(A)
Output:
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
Arrays
Arrays are the R data objects which store the data in more than two dimensions. Arrays are n-
dimensional data structures. For example, if we create an array of dimensions (2, 3, 3) then it
creates 3 rectangular matrices each with 2 rows and 3 columns. They are homogeneous data
structures.
Now, let’s see how to create arrays in R. To create an array in R you need to use the function
called array(). The arguments to this array() are the set of elements in vectors and you have to
pass a vector containing the dimensions of the array.
Example:
A = array(
c(1, 2, 3, 4, 5, 6, 7, 8),
dim = c(2, 2, 2)
)
print(A)
Output:
,,1
[,1] [,2]
[1,] 1 3
[2,] 2 4
,,2
[,1] [,2]
[1,] 5 7
[2,] 6 8
Factors
Factors are the data objects which are used to categorize the data and store it as levels. They
are useful for storing categorical data. They can store both strings and integers. They are
useful to categorize unique values in columns like “TRUE” or “FALSE”, or “MALE” or
“FEMALE”, etc.. They are useful in data analysis for statistical modeling.
Now, let’s see how to create factors in R. To create a factor in R you need to use the function
called factor(). The argument to this factor() is the vector.
Example:
fac = factor(c("Male", "Female", "Male",
"Male", "Female", "Male", "Female"))
print(fac)
Output:
[1] Male Female Male Male Female Male Female
Levels: Female Male
Decision Making
Decision making decides the flow of the execution of the program based on certain
conditions. In decision making programmer needs to provide some condition which is
evaluated by the program, along with it there also provided some statements which are
executed if the condition is true and optionally other statements if the condition is evaluated
to be false.
Example 2: Demonstrating if-else-if and nested if
a <- 10
if (a == 11)
{
print ("a is 11")
} else if (a==10)
{
print ("a is 10")
} else
print ("a is not present")
if (a %% 2 == 0)
{
if (a %% 5 == 0)
print("Number is divisible by both 2 and 5")
}
Output:
[1] "a is 10"
[1] "Number is divisible by both 2 and 5"
Control Flow
Loops are used wherever we have to execute a block of statements repeatedly. For example,
printing “hello world” 10 times. The different types of loops in R are –
For Loop
# R Program to demonstrate the use of
# for loop along with concatenate
for (i in c(-8, 9, 11, 45))
{
print(i)
}
Output:
[1] -8
[1] 9
[1] 11
[1] 45
While Loop
val = 1
while (val <= 5 )
{
# statements
print(val)
val = val + 1
}
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
Repeat Loop
val = 1
repeat
{
print(val)
val = val + 1
if(val > 5){
break
}
}
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
Note: For more information, refer Loops in R
Loop Control Statements
Loop control statements change execution from its normal sequence. Following are the loop
control statements provided by R Language:
Next Statement: The next statement is used to skip the current iteration in the loop and move
to the next iteration without exiting from the loop itself.
no <- 15:20
for (val in no){
if (val == 17){
break
}
print(paste("Values are: ", val))
}
print("------------------------------------")
for (val in no){
if (val == 17){
next
}
print(paste("Values are: ", val))
}
Output:
[1] "Values are: 15"
[1] "Values are: 16"
[1] "------------------------------------"
[1] "Values are: 15"
[1] "Values are: 16"
[1] "Values are: 18"
[1] "Values are: 19"
[1] "Values are: 20"
Functions
Functions are the block of code that given the user the ability to reuse the same code which
saves the excessive use of memory and provides better readability to the code. So basically, a
function is a collection of statements that perform some specific task and return the result to
the caller. Functions are created in R by using the command function() keyword
Function with Arguments:
Arguments to a function can be specified at the time of function definition, after the function
name, inside the parenthesis.
evenOdd = function(x){
if(x %% 2 == 0)
return("even")
else
return("odd")
}
divisible <- function(a, b){
if(a %% b == 0){
cat(a, "is divisible by", b, "\n")
} else{
cat(a, "is not divisible by", b, "\n")
}
}
# function with single argument
print(evenOdd(4))
print(evenOdd(3))
# function with multiple arguments
divisible(7, 3)
divisible(36, 6)
divisible(9, 2)
Output:
[1] "even"
[1] "odd"
7 is not divisible by 3
36 is divisible by 6
9 is not divisible by 2
Default Arguments: Default value in a function is a value that is not required to specify each
time the function is called.
isdivisible <- function(a, b = 9){
if(a %% b == 0){
cat(a, "is divisible by", b, "\n")
} else{
cat(a, "is not divisible by", b, "\n")
}
}
isdivisible(20, 2)
isdivisible(12)
Output:
20 is divisible by 2
12 is not divisible by 9
Variable length arguments: Dots argument (…) is also known as ellipsis which allows the
function to take an undefined number of arguments.
fun <- function(n, ...){
l <- c(n, ...)
paste(l, collapse = " ")
}
fun(5, 1L, 6i, TRUE, "GFG", 1:2)
Output:
5 1 0+6i TRUE GFG 1 2
File Handling in R Programming
In R Programming, handling of files such as reading and writing files can be done by using
in-built functions present in R base package. In this article, let us discuss reading and writing
of CSV files, creating a file, renaming a file, check the existence of the file, listing all files in
the working directory, copying files and creating directories.
Creating a File
Using [Link]() function, a new file can be created from console or truncates if already
exists. The function returns a TRUE logical value if file is created otherwise, returns FALSE.
[Link]("[Link]")
Output:
[1] TRUE
Writing into a File
[Link]() function in R programming is used to write an object to a file. This function is
present in utils package in R and writes data frame or matrix object to any type of file.
[Link](x = iris[1:10, ],
file = "[Link]")
Output:
Renaming a File
The [Link]() function renames the file and return a logical value. The function renames
files but not directories.
[Link]("[Link]", "[Link]")
Output:
[1] TRUE
Check Existence of a File
A file exists or not in current working directory can be checked using [Link]() function. It
returns TRUE logical value if file exists, otherwise returns FALSE.
[Link]("[Link]")
[Link]("[Link]")
Output:
[1] FALSE
[1] TRUE
Reading a File
Using [Link]() function in R, files can be read and output is shown as dataframe. This
functions helps in analyzing the dataframe for further computations.
[Link] <- [Link](file = "[Link]")
print([Link])
X [Link] [Link] [Link] [Link] Species
1 1 5.1 3.5 1.4 0.2 setosa
2 2 4.9 3.0 1.4 0.2 setosa
3 3 4.7 3.2 1.3 0.2 setosa
4 4 4.6 3.1 1.5 0.2 setosa
5 5 5.0 3.6 1.4 0.2 setosa
6 6 5.4 3.9 1.7 0.4 setosa
7 7 4.6 3.4 1.4 0.3 setosa
8 8 5.0 3.4 1.5 0.2 setosa
9 9 4.4 2.9 1.4 0.2 setosa
10 10 4.9 3.1 1.5 0.1 setosa
Copy a File
[Link]("C:/Users/Utkarsh/Documents/[Link]", "E:/")
[Link]("E:/")
Output:
[1] TRUE
[1] "$[Link]" "Counter-Strike Global Offensive"
[3] "Home" "[Link]"
[5] "System Volume Information"
Create a Directory
The [Link]() function creates a directory in the path specified in the function parameter. If
path is not specified in function parameter, directory is created in current working directory.
[Link]("GFG")
[Link]()
Output:
[1] "Bandicam" "Bluetooth Folder"
[3] "[Link]" "Custom Office Templates"
[5] "[Link]" "GFG"
[7] "[Link]" "My Music"
[9] "My Pictures" "My Videos"
[11] "[Link]" "Visual Studio 2012"
CSV Files
R CSV Files are text files wherein the values of each row are separated by a delimiter, as in a
comma or a tab. In this article, we will use the following sample CSV file.
Getting and Setting the Working Directory with R CSV Files
print(getwd())
setwd("/web/com")
print(getwd())
Output:
[1] "C:/Users/GFG19565/Documents"
[1] "C:/Users/GFG19565/Documents"
With the help of getwd() function we can get the current working directory and with the help
of setwd()function we can also set a new working directory.
Input as R CSV Files
id, name, department, salary, projects
1, A, IT, 60754, 4
2, B, Tech, 59640, 2
3, C, Marketing, 69040, 8
4, D, Marketing, 65043, 5
We can save this file in notepad and give name [Link] so we can upload this in R
Programming Language.
Reading a R CSV Files
The contents of a CSV file can be read as a data frame in R using the [Link](…) function.
The CSV file to be read should be either present in the current working directory or the
directory should be set accordingly using the setwd(…) command in R. The CSV file can
also be read from a URL using [Link]() function.
csv_data <- [Link](file = 'C:\\Users\\GFG19565\\Downloads\\[Link]')
print(csv_data)
print (ncol(csv_data))
print(nrow(csv_data))
Output:
id, name, department, salary, projects
1 1 A HR 60754 14
2 2 B Tech 59640 3
3 3 C Marketing 69040 8
4 4 D HR 65043 5
5 5 E Tech 59943 2
[1] 4
[1] 7
We can upload the R Csv Files by passing its directory the header is by default set to a TRUE
value in the function. The head is not included in the count of rows, therefore this CSV has 7
rows and 4 columns.
Writing into a R CSV Files
The contents of the data frame can be written into a CSV file. The CSV file is stored in the
current working directory with the name specified in the function [Link](data frame,
output CSV name) in R.
result <- tapply(csv_data$salary, csv_data$department, mean)
print(result)
Output:
HR IT Marketing Tech
69000.0 62877.0 67041.5 59791.5
In this we will Calculating the average salary for each department.