Introduction to R Programming Basics
Introduction to R Programming Basics
The core of R is an interpreted computer language which allows branching and looping as
well as modular programming using functions. R allows integration with the procedures
written in the C, C++, .Net, Python or FORTRAN languages for efficiency.
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.
R is free software distributed under a GNU-style copy left, and an official part of the GNU
project called GNU S.
Evolution of R
R was initially written by Ross Ihaka and Robert Gentleman at the Department of
Statistics of the University of Auckland in Auckland, New Zealand. R made its first
appearance in 1993.
• A large group of individuals has contributed to R by sending code and bug reports.
• Since mid-1997 there has been a core group (the "R Core Team") who can modify
the R source code archive.
Features of R
As stated earlier, R is a programming language and software environment for statistical
analysis, graphics representation and reporting.
R - Basic Syntax
As a convention, we will start learning R programming by writing a "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. Let's check both one by one.
R Command Prompt
Once you have R environment setup, then it’s easy to start your R command prompt by
just typing the following command at your command prompt −
$R
This will launch R interpreter and you will get a prompt > where you can start typing your
program as follows −
Here first statement defines a string variable myString, where we assign a string "Hello,
World!" and then next statement print() is being used to print the value stored in variable
myString.
R Script File
Usually, you will do your programming by writing your programs in script files and then you
execute those scripts at your command prompt with the help of R interpreter
called Rscript. So let's start with writing following code in a text file called test. R as
under−
Save the above code in a file test.R and execute it at Linux command prompt as given
below. Even if you are using Windows or other system, syntax will remain same.
$ Rscript test.R
When we run the above program, it produces the following result.
R - Data Types
Variables are nothing but reserved memory locations to store values. This means that,
when you create a variable you reserve some space in memory.
You may like to store information of various data types like character, wide character,
integer, floating point, double floating point, Boolean etc. Based on the data type of a
variable, the operating system allocates memory and decides what can be stored in the
reserved memory.
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 Verify
Logical TRUE, FALSE v <- TRUE
print(class(v))
it produces the following result −
[1] "logical"
Numeric 12.3, 5, 999 v <- 23.5
print(class(v))
it produces the following result −
[1] "numeric"
Integer 2L, 34L, 0L v <- 2L
print(class(v))
it produces the following result −
[1] "integer"
Complex 3 + 2i v <- 2+5i
print(class(v))
it produces the following result −
[1] "complex"
Character 'a' , '"good", "TRUE", '23.4' v <- "TRUE"
print(class(v))
it produces the following result −
[1] "character"
Raw "Hello" is stored as 48 65 6c 6c 6f v <- charToRaw("Hello")
print(class(v))
it produces the following result −
[1] "raw"
In R programming, the very basic data types are the R-objects called vectors which hold
elements of different classes as shown above. Please note in R the number of classes is
not confined to only the above six types. For example, we can use many atomic vectors
and create an array whose class will become array.
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.
# Create a vector.
apple <- c('red','green',"yellow")
print(apple)
# Get the class of the vector.
print(class(apple))
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.
# Create a list.
list1 <- list(c(2,5,3),21.3,sin)
# Print the list.
print(list1)
Matrices
A matrix is a two-dimensional rectangular data set. It can be created using a vector input to
the matrix function.
# Create a matrix.
M = matrix( c('a','a','b','c','b','a'), nrow = 2, ncol = 3, byrow = TRUE)
print(M)
# Create an array.
a <- array(c('green','yellow'),dim = c(3,3,2))
print(a)
,,1
[,1] [,2] [,3]
[1,] "green" "yellow" "green"
[2,] "yellow" "green" "yellow"
[3,] "green" "yellow" "green"
,,2
[,1] [,2] [,3]
[1,] "yellow" "green" "yellow"
[2,] "green" "yellow" "green"
[3,] "yellow" "green" "yellow"
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))
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 [Link]() function.
# Create the data frame.
BMI <- [Link](
gender = c("Male", "Male","Female"),
height = c(152, 171.5, 165),
weight = c(81,93, 78),
Age = c(42,38,26)
)
print(BMI)
R – Variables
A variable provides us with named storage that our programs can manipulate. A variable in
R can store an atomic vector, group of atomic vectors or a combination of many Robjects.
A valid variable name consists of letters, numbers and the dot or underline characters. The
variable name starts with a letter or the dot not followed by a number.
var_name% Invalid Has the character '%'. Only dot(.) and underscore allowed.
.var_name, valid Can start with a dot(.) but the dot(.)should not be followed by a
[Link] number
[1] 0 1 2 3
var.1 is 0 1 2 3
var.2 is learn R
var.3 is 1 1
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.
Finding Variables
To know all the variables currently available in the workspace we use the ls()function. Also
the ls() function can use patterns to match the variable names.
print(ls())
The ls() function can use patterns to match the variable names.
print(ls(pattern = "var"))
print(ls([Link] = TRUE))
Deleting Variables
Variables can be deleted by using the rm() function. Below we delete the variable var.3.
On printing the value of the variable error is thrown.
rm(var.3)
print(var.3)
When we execute the above code, it produces the following result −
[1] "var.3"
Error in print(var.3) : object 'var.3' not found
All the variables can be deleted by using the rm() and ls() function together.
rm(list = ls())
print(ls())
When we execute the above code, it produces the following result −
character(0)
R - 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 −
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Assignment Operators
• Miscellaneous Operators
Arithmetic Operators
Following table shows the arithmetic operators supported by R language. The operators
act on each element of the vector.
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.
Operator Description Example
> Checks if each element of the first v <- c(2,5.5,6,9)
vector is greater than the corresponding t <- c(8,2.5,14,9)
element of the second vector. print(v>t)
it produces the following result −
[1] FALSE TRUE FALSE FALSE
< Checks if each element of the first v <- c(2,5.5,6,9)
vector is less than the corresponding t <- c(8,2.5,14,9)
element of the second vector. print(v < t)
it produces the following result −
[1] TRUE FALSE TRUE FALSE
== Checks if each element of the first v <- c(2,5.5,6,9)
vector is equal to the corresponding t <- c(8,2.5,14,9)
element of the second vector. print(v == t)
it produces the following result −
[1] FALSE FALSE FALSE TRUE
<= Checks if each element of the first v <- c(2,5.5,6,9)
vector is less than or equal to the t <- c(8,2.5,14,9)
corresponding element of the second print(v<=t)
vector.
it produces the following result −
[1] TRUE FALSE TRUE TRUE
>= Checks if each element of the first v <- c(2,5.5,6,9)
vector is greater than or equal to the t <- c(8,2.5,14,9)
corresponding element of the second print(v>=t)
vector.
it produces the following result −
[1] FALSE TRUE FALSE TRUE
!= Checks if each element of the first v <- c(2,5.5,6,9)
vector is unequal to the corresponding t <- c(8,2.5,14,9)
element of the second vector. print(v!=t)
it produces the following result −
[1] TRUE TRUE TRUE FALSE
Logical Operators
Following table shows the logical operators supported by R language. 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.
Operator Description Example
& It is called Element-wise Logical AND v <- c(3,1,TRUE,2+3i)
operator. It combines each element of the t <- c(4,1,FALSE,2+3i)
first vector with the corresponding print(v&t)
element of the second vector and gives a
output TRUE if both the elements are it produces the following result −
TRUE. [1] TRUE TRUE FALSE TRUE
| It is called Element-wise Logical OR v <- c(3,0,TRUE,2+2i)
operator. It combines each element of the t <- c(4,0,FALSE,2+3i)
first vector with the corresponding print(v|t)
element of the second vector and gives a
output TRUE if one the elements is it produces the following result −
TRUE. [1] TRUE FALSE TRUE TRUE
! It is called Logical NOT operator. Takes v <- c(3,0,TRUE,2+2i)
each element of the vector and gives the print(!v)
opposite logical value.
it produces the following result −
[1] FALSE TRUE FALSE FALSE
The logical operator && and || considers only the first element of the vectors and give a
vector of single element as output.
Operator Description Example
&& Called Logical AND operator. Takes first v <- c(3,0,TRUE,2+2i)
element of both the vectors and gives the t <- c(1,3,TRUE,2+3i)
TRUE only if both are TRUE. print(v&&t)
it produces the following result −
[1] TRUE
|| Called Logical OR operator. Takes first v <- c(0,0,TRUE,2+2i)
element of both the vectors and gives the t <- c(0,3,TRUE,2+3i)
TRUE if one of them is TRUE. print(v||t)
it produces the following result −
[1] FALSE
Assignment Operators
These operators are used to assign values to vectors.
Operator Description Example
<− Called Left Assignment v1 <- c(3,1,TRUE,2+3i)
or v2 <<- c(3,1,TRUE,2+3i)
= v3 = c(3,1,TRUE,2+3i)
or print(v1)
<<− print(v2)
print(v3)
it produces the following result −
[1] 3+0i 1+0i 1+0i 2+3i
[1] 3+0i 1+0i 1+0i 2+3i
[1] 3+0i 1+0i 1+0i 2+3i
-> Called Right Assignment c(3,1,TRUE,2+3i) -> v1
or c(3,1,TRUE,2+3i) ->> v2
->> print(v1)
print(v2)
it produces the following result −
[1] 3+0i 1+0i 1+0i 2+3i
[1] 3+0i 1+0i 1+0i 2+3i
Miscellaneous Operators
These operators are used to for specific purpose and not general mathematical or logical
computation.
Operator Description Example
: Colon operator. It v <- 2:8
creates the series print(v)
of numbers in
sequence for a it produces the following result −
vector. [1] 2 3 4 5 6 7 8
%in% This operator is v1 <- 8
used to identify if v2 <- 12
an element belongs t <- 1:10
to a vector. print(v1 %in% t)
print(v2 %in% t)
it produces the following result −
[1] TRUE
[1] FALSE
%*% This operator is M = matrix( c(2,6,5,1,10,4), nrow = 2,ncol = 3,byrow = TRUE)
used to multiply a t = M %*% t(M)
matrix with its print(t)
transpose.
it produces the following result −
[,1] [,2]
[1,] 65 82
[2,] 82 117
R - Decision making
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 −
Example
x <- switch(
3,
"first",
"second",
"third",
"fourth"
)
print(x)
When the above code is compiled and executed, it produces the following result −
[1] "third"
R - Loops
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 −
R programming language provides the following kinds of loop to handle looping
requirements.
[Link] Loop Type & Description
1 repeat loop The Repeat loop executes the same code again and again until a stop condition
is met.
Syntax
repeat {
commands
if(condition) {
break
}
}
Example
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"
2 while loop
The While loop executes the same code again and again until a stop condition is met. It tests
the condition before executing the loop body.
Syntax
while (test_expression) {
statement
}
Example
v <- c("Hello","while loop")
cnt <- 2
R supports the following control statements. Click the following links to check their detail.
[Link]. Control Statement & Description
1 break statement
Terminates the loop statement and transfers execution to the statement immediately
following the loop.
2 Next statement
The next statement simulates the behavior of R switch.
R – 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.
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 Definition
An R function is created by using the keyword function. The basic syntax of an R function
definition is as follows −
• Function Body − The function body contains a collection of statements that defines
what the function does.
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.
[1] 32 33 34 35 36 37 38 39 40 41 42 43 44
[1] 53.5
[1] 1526
User-defined Function
We can create user-defined functions in R. They are specific to what a user wants and
once created they can be used like the built-in functions. Below is an example of how a
function is created and used.
[1] 1
[1] 4
[1] 9
[1] 16
[1] 25
Calling a Function with Argument Values (by position and by name)
The arguments to a function call can be supplied in the same sequence as defined in the
function or they can be supplied in a different sequence but assigned to the names of the
arguments.
[1] 26
[1] 58
[1] 18
[1] 45
[1] 36
[1] 6
Error in print(b) : argument "b" is missing, with no default
Experiment No. 1 Date:
Aim: Load the ‘iris. CSV’ file and display the names and type of each column. Find
statistics such as min, max, range, mean, median, variance, standard deviation for
each column of data.
Now if we want to export this iris data set as a csv file we can do it as below
Export to CSV in R
If you want to set your working directory to a folder of your choice use
Syntax:
setwd()
Example:
> setwd("c:/x/")
We can import this iris data set in a csv file by using [Link]() function:
Syntax:
?[Link]()
It opens help window of [Link] function.
Syntax:
[Link]() - It is used to read csv files and create a data frame from it.
We import iris data by giving path of data file of "[Link]" .
Example:
iris<- [Link]("C:\\x\\[Link]")
Display the names of each column of iris data:
> colnames(iris)
[1] "X" "[Link]" "[Link]" "[Link]" "[Link]" "Species"
> typeof(iris$[Link])
[1] "double"
> typeof(iris$[Link])
[1] "double"
> typeof(iris$[Link])
[1] "double"
> typeof(iris$[Link])
[1] "double"
> typeof(iris$Species)
[1] "integer"
> apply(iris,2,min)
X [Link] [Link] [Link] [Link] Species
" 1" "4.3" "2.0" "1.0" "0.1" "setosa"
> apply(iris,2,max)
X [Link] [Link] [Link] [Link] Species
"150" "7.9" "4.4" "6.9" "2.5" "virginica"
> apply(iris,2,range)
X [Link] [Link] [Link] [Link] Species
[1,] " 1" "4.3" "2.0" "1.0" "0.1" "setosa"
[2,] "150" "7.9" "4.4" "6.9" "2.5" "virginica"
Mean
It is calculated by taking the sum of the values and dividing with the number of values in a
data series.
The mean of an observation variable is a numerical measure of the central location of the
data values. It is the sum of its data values divided by data count.
Hence, for a data sample of size n, its sample mean is defined as follows:
Similarly, for a data population of size N, the population mean is:
Median
The middle most value in a data series is called the median. The median() function is used
in R to calculate this value.
Syntax
The basic syntax for calculating median in R is −
median (x, [Link] = FALSE)
Following is the description of the parameters used −
• x is the input vector.
• [Link] is used to remove the missing values from the input vector.
Example
# Create the vector.
x <- c(12,7,3,4.2,18,2,54,-21,8,-5)
# Find the median.
[Link] <- median(x)
print([Link])
Variance
The variance is a numerical measure of how the data values is dispersed around the mean.
In particular, the sample variance is defined as:
Similarly, the population variance is defined in terms of the population mean μ and
population size N:
Standard Deviation
The standard deviation of an observation variable is the square root of its variance. This
function computes the standard deviation of the values in x. If [Link] is TRUE then missing
values are removed before computation proceeds.
Syntax:
sd(x, [Link] = FALSE)
Following is the description of the parameters used −
• X is a numeric vector or an R object which is coercible to one by [Link](x).
• [Link] logical. Should missing values be removed?
Aim: Write R program to normalize the variables into 0 to 1 scale using min-max
normalization.
Normalization
Normalization or scaling refers to bringing all the columns into same range.
Min-Max normalization:
It is simple way of scaling values in a column. But, it tries to move the values towards the
mean of the column. Here is the formula
print(normalize(mydf,cols))
Output:
X [Link] [Link] [Link] [Link] Species
1 1 -0.89767388 1.01560199 -1.33575163 -1.3110521482 setosa
2 2 -1.13920048 -0.13153881 -1.33575163 -1.3110521482 setosa
3 3 -1.38072709 0.32731751 -1.39239929 -1.3110521482 setosa
4 4 -1.50149039 0.09788935 -1.27910398 -1.3110521482 setosa
5 5 -1.01843718 1.24503015 -1.33575163 -1.3110521482 setosa
6 6 -0.53538397 1.93331463 -1.16580868 -1.0486667950 setosa
7 7 -1.50149039 0.78617383 -1.33575163 -1.1798594716 setosa
8 8 -1.01843718 0.78617383 -1.27910398 -1.3110521482 setosa
9 9 -1.74301699 -0.36096697 -1.33575163 -1.3110521482 setosa
10 10 -1.13920048 0.09788935 -1.27910398 -1.4422448248 setosa
11 11 -0.53538397 1.47445831 -1.27910398 -1.3110521482 setosa
12 12 -1.25996379 0.78617383 -1.22245633 -1.3110521482 setosa
13 13 -1.25996379 -0.13153881 -1.33575163 -1.4422448248 setosa
14 14 -1.86378030 -0.13153881 -1.50569459 -1.4422448248 setosa
15 15 -0.05233076 2.16274279 -1.44904694 -1.3110521482 setosa
16 16 -0.17309407 3.08045544 -1.27910398 -1.0486667950 setosa
17 17 -0.53538397 1.93331463 -1.39239929 -1.0486667950 setosa
18 18 -0.89767388 1.01560199 -1.33575163 -1.1798594716 setosa
19 19 -0.17309407 1.70388647 -1.16580868 -1.1798594716 setosa
20 20 -0.89767388 1.70388647 -1.27910398 -1.1798594716 setosa
21 21 -0.53538397 0.78617383 -1.16580868 -1.3110521482 setosa
22 22 -0.89767388 1.47445831 -1.27910398 -1.0486667950 setosa
23 23 -1.50149039 1.24503015 -1.56234224 -1.3110521482 setosa
24 24 -0.89767388 0.55674567 -1.16580868 -0.9174741184 setosa
25 25 -1.25996379 0.78617383 -1.05251337 -1.3110521482 setosa
26 26 -1.01843718 -0.13153881 -1.22245633 -1.3110521482 setosa
27 27 -1.01843718 0.78617383 -1.22245633 -1.0486667950 setosa
28 28 -0.77691058 1.01560199 -1.27910398 -1.3110521482 setosa
29 29 -0.77691058 0.78617383 -1.33575163 -1.3110521482 setosa
30 30 -1.38072709 0.32731751 -1.22245633 -1.3110521482 setosa
31 31 -1.25996379 0.09788935 -1.22245633 -1.3110521482 setosa
32 32 -0.53538397 0.78617383 -1.27910398 -1.0486667950 setosa
33 33 -0.77691058 2.39217095 -1.27910398 -1.4422448248 setosa
34 34 -0.41462067 2.62159911 -1.33575163 -1.3110521482 setosa
35 35 -1.13920048 0.09788935 -1.27910398 -1.3110521482 setosa
36 36 -1.01843718 0.32731751 -1.44904694 -1.3110521482 setosa
37 37 -0.41462067 1.01560199 -1.39239929 -1.3110521482 setosa
38 38 -1.13920048 1.24503015 -1.33575163 -1.4422448248 setosa
39 39 -1.74301699 -0.13153881 -1.39239929 -1.3110521482 setosa
40 40 -0.89767388 0.78617383 -1.27910398 -1.3110521482 setosa
41 41 -1.01843718 1.01560199 -1.39239929 -1.1798594716 setosa
42 42 -1.62225369 -1.73753594 -1.39239929 -1.1798594716 setosa
43 43 -1.74301699 0.32731751 -1.39239929 -1.3110521482 setosa
44 44 -1.01843718 1.01560199 -1.22245633 -0.7862814418 setosa
45 45 -0.89767388 1.70388647 -1.05251337 -1.0486667950 setosa
46 46 -1.25996379 -0.13153881 -1.33575163 -1.1798594716 setosa
47 47 -0.89767388 1.70388647 -1.22245633 -1.3110521482 setosa
48 48 -1.50149039 0.32731751 -1.33575163 -1.3110521482 setosa
49 49 -0.65614727 1.47445831 -1.27910398 -1.3110521482 setosa
50 50 -1.01843718 0.55674567 -1.33575163 -1.3110521482 setosa
51 51 1.39682886 0.32731751 0.53362088 0.2632599711 versicolor
52 52 0.67224905 0.32731751 0.42032558 0.3944526477 versicolor
53 53 1.27606556 0.09788935 0.64691619 0.3944526477 versicolor
54 54 -0.41462067 -1.73753594 0.13708732 0.1320672944 versicolor
55 55 0.79301235 -0.59039513 0.47697323 0.3944526477 versicolor
56 56 -0.17309407 -0.59039513 0.42032558 0.1320672944 versicolor
57 57 0.55148575 0.55674567 0.53362088 0.5256453243 versicolor
58 58 -1.13920048 -1.50810778 -0.25944625 -0.2615107354 versicolor
59 59 0.91377565 -0.36096697 0.47697323 0.1320672944 versicolor
60 60 -0.77691058 -0.81982329 0.08043967 0.2632599711 versicolor
61 61 -1.01843718 -2.42582042 -0.14615094 -0.2615107354 versicolor
62 62 0.06843254 -0.13153881 0.25038262 0.3944526477 versicolor
63 63 0.18919584 -1.96696410 0.13708732 -0.2615107354 versicolor
64 64 0.30995914 -0.36096697 0.53362088 0.2632599711 versicolor
65 65 -0.29385737 -0.36096697 -0.08950329 0.1320672944 versicolor
66 66 1.03453895 0.09788935 0.36367793 0.2632599711 versicolor
67 67 -0.29385737 -0.13153881 0.42032558 0.3944526477 versicolor
68 68 -0.05233076 -0.81982329 0.19373497 -0.2615107354 versicolor
69 69 0.43072244 -1.96696410 0.42032558 0.3944526477 versicolor
70 70 -0.29385737 -1.27867961 0.08043967 -0.1303180588 versicolor
71 71 0.06843254 0.32731751 0.59026853 0.7880306775 versicolor
72 72 0.30995914 -0.59039513 0.13708732 0.1320672944 versicolor
73 73 0.55148575 -1.27867961 0.64691619 0.3944526477 versicolor
74 74 0.30995914 -0.59039513 0.53362088 0.0008746178 versicolor
75 75 0.67224905 -0.36096697 0.30703027 0.1320672944 versicolor
76 76 0.91377565 -0.13153881 0.36367793 0.2632599711 versicolor
77 77 1.15530226 -0.59039513 0.59026853 0.2632599711 versicolor
78 78 1.03453895 -0.13153881 0.70356384 0.6568380009 versicolor
79 79 0.18919584 -0.36096697 0.42032558 0.3944526477 versicolor
80 80 -0.17309407 -1.04925145 -0.14615094 -0.2615107354 versicolor
81 81 -0.41462067 -1.50810778 0.02379201 -0.1303180588 versicolor
82 82 -0.41462067 -1.50810778 -0.03285564 -0.2615107354 versicolor
83 83 -0.05233076 -0.81982329 0.08043967 0.0008746178 versicolor
84 84 0.18919584 -0.81982329 0.76021149 0.5256453243 versicolor
85 85 -0.53538397 -0.13153881 0.42032558 0.3944526477 versicolor
86 86 0.18919584 0.78617383 0.42032558 0.5256453243 versicolor
87 87 1.03453895 0.09788935 0.53362088 0.3944526477 versicolor
88 88 0.55148575 -1.73753594 0.36367793 0.1320672944 versicolor
89 89 -0.29385737 -0.13153881 0.19373497 0.1320672944 versicolor
90 90 -0.41462067 -1.27867961 0.13708732 0.1320672944 versicolor
91 91 -0.41462067 -1.04925145 0.36367793 0.0008746178 versicolor
92 92 0.30995914 -0.13153881 0.47697323 0.2632599711 versicolor
93 93 -0.05233076 -1.04925145 0.13708732 0.0008746178 versicolor
94 94 -1.01843718 -1.73753594 -0.25944625 -0.2615107354 versicolor
95 95 -0.29385737 -0.81982329 0.25038262 0.1320672944 versicolor
96 96 -0.17309407 -0.13153881 0.25038262 0.0008746178 versicolor
97 97 -0.17309407 -0.36096697 0.25038262 0.1320672944 versicolor
98 98 0.43072244 -0.36096697 0.30703027 0.1320672944 versicolor
99 99 -0.89767388 -1.27867961 -0.42938920 -0.1303180588 versicolor
100 100 -0.17309407 -0.59039513 0.19373497 0.1320672944 versicolor
101 101 0.55148575 0.55674567 1.27004036 1.7063794137 virginica
102 102 -0.05233076 -0.81982329 0.76021149 0.9192233541 virginica
103 103 1.51759216 -0.13153881 1.21339271 1.1816087073 virginica
104 104 0.55148575 -0.36096697 1.04344975 0.7880306775 virginica
105 105 0.79301235 -0.13153881 1.15674505 1.3128013839 virginica
106 106 2.12140867 -0.13153881 1.60992627 1.1816087073 virginica
107 107 -1.13920048 -1.27867961 0.42032558 0.6568380009 virginica
108 108 1.75911877 -0.36096697 1.43998331 0.7880306775 virginica
109 109 1.03453895 -1.27867961 1.15674505 0.7880306775 virginica
110 110 1.63835547 1.24503015 1.32668801 1.7063794137 virginica
111 111 0.79301235 0.32731751 0.76021149 1.0504160307 virginica
112 112 0.67224905 -0.81982329 0.87350679 0.9192233541 virginica
113 113 1.15530226 -0.13153881 0.98680210 1.1816087073 virginica
114 114 -0.17309407 -1.27867961 0.70356384 1.0504160307 virginica
115 115 -0.05233076 -0.59039513 0.76021149 1.5751867371 virginica
116 116 0.67224905 0.32731751 0.87350679 1.4439940605 virginica
117 117 0.79301235 -0.13153881 0.98680210 0.7880306775 virginica
118 118 2.24217198 1.70388647 1.66657392 1.3128013839 virginica
119 119 2.24217198 -1.04925145 1.77986923 1.4439940605 virginica
120 120 0.18919584 -1.96696410 0.70356384 0.3944526477 virginica
121 121 1.27606556 0.32731751 1.10009740 1.4439940605 virginica
122 122 -0.29385737 -0.59039513 0.64691619 1.0504160307 virginica
123 123 2.24217198 -0.59039513 1.66657392 1.0504160307 virginica
124 124 0.55148575 -0.81982329 0.64691619 0.7880306775 virginica
125 125 1.03453895 0.55674567 1.10009740 1.1816087073 virginica
126 126 1.63835547 0.32731751 1.27004036 0.7880306775 virginica
127 127 0.43072244 -0.59039513 0.59026853 0.7880306775 virginica
128 128 0.30995914 -0.13153881 0.64691619 0.7880306775 virginica
129 129 0.67224905 -0.59039513 1.04344975 1.1816087073 virginica
130 130 1.63835547 -0.13153881 1.15674505 0.5256453243 virginica
131 131 1.87988207 -0.59039513 1.32668801 0.9192233541 virginica
132 132 2.48369858 1.70388647 1.49663097 1.0504160307 virginica
133 133 0.67224905 -0.59039513 1.04344975 1.3128013839 virginica
134 134 0.55148575 -0.59039513 0.76021149 0.3944526477 virginica
135 135 0.30995914 -1.04925145 1.04344975 0.2632599711 virginica
136 136 2.24217198 -0.13153881 1.32668801 1.4439940605 virginica
137 137 0.55148575 0.78617383 1.04344975 1.5751867371 virginica
138 138 0.67224905 0.09788935 0.98680210 0.7880306775 virginica
139 139 0.18919584 -0.13153881 0.59026853 0.7880306775 virginica
140 140 1.27606556 0.09788935 0.93015445 1.1816087073 virginica
141 141 1.03453895 0.09788935 1.04344975 1.5751867371 virginica
142 142 1.27606556 0.09788935 0.76021149 1.4439940605 virginica
143 143 -0.05233076 -0.81982329 0.76021149 0.9192233541 virginica
144 144 1.15530226 0.32731751 1.21339271 1.4439940605 virginica
145 145 1.03453895 0.55674567 1.10009740 1.7063794137 virginica
146 146 1.03453895 -0.13153881 0.81685914 1.4439940605 virginica
147 147 0.55148575 -1.27867961 0.70356384 0.9192233541 virginica
148 148 0.79301235 -0.13153881 0.81685914 1.0504160307 virginica
149 149 0.43072244 0.78617383 0.93015445 1.4439940605 virginica
150 150 0.06843254 -0.13153881 0.76021149 0.7880306775 virginica
b) By using min max normalization on each column
Example:
Output:
[1] 0.22222222 0.16666667 0.11111111 0.08333333 0.19444444 0.30555556 0.08333333
0.19444444
[9] 0.02777778 0.16666667 0.30555556 0.13888889 0.13888889 0.00000000 0.41666667
0.38888889
[17] 0.30555556 0.22222222 0.38888889 0.22222222 0.30555556 0.22222222
0.08333333 0.22222222
[25] 0.13888889 0.19444444 0.19444444 0.25000000 0.25000000 0.11111111
0.13888889 0.30555556
[33] 0.25000000 0.33333333 0.16666667 0.19444444 0.33333333 0.16666667
0.02777778 0.22222222
[41] 0.19444444 0.05555556 0.02777778 0.19444444 0.22222222 0.13888889
0.22222222 0.08333333
[49] 0.27777778 0.19444444 0.75000000 0.58333333 0.72222222 0.33333333
0.61111111 0.38888889
[57] 0.55555556 0.16666667 0.63888889 0.25000000 0.19444444 0.44444444
0.47222222 0.50000000
[65] 0.36111111 0.66666667 0.36111111 0.41666667 0.52777778 0.36111111
0.44444444 0.50000000
[73] 0.55555556 0.50000000 0.58333333 0.63888889 0.69444444 0.66666667
0.47222222 0.38888889
[81] 0.33333333 0.33333333 0.41666667 0.47222222 0.30555556 0.47222222
0.66666667 0.55555556
[89] 0.36111111 0.33333333 0.33333333 0.50000000 0.41666667 0.19444444
0.36111111 0.38888889
[97] 0.38888889 0.52777778 0.22222222 0.38888889 0.55555556 0.41666667
0.77777778 0.55555556
[105] 0.61111111 0.91666667 0.16666667 0.83333333 0.66666667 0.80555556
0.61111111 0.58333333
[113] 0.69444444 0.38888889 0.41666667 0.58333333 0.61111111 0.94444444
0.94444444 0.47222222
[121] 0.72222222 0.36111111 0.94444444 0.55555556 0.66666667 0.80555556
0.52777778 0.50000000
[129] 0.58333333 0.80555556 0.86111111 1.00000000 0.58333333 0.55555556
0.50000000 0.94444444
[137] 0.55555556 0.58333333 0.47222222 0.72222222 0.66666667 0.72222222
0.41666667 0.69444444
[145] 0.66666667 0.66666667 0.55555556 0.61111111 0.52777778 0.44444444
Experiment No. 3 Date:
Aim: Generate histograms for any one variable (sepal length/ sepal width/ petal
length/ petal width) and generate scatter plots for every pair of variables showing
each species in different color
R – Histograms
A histogram represents the frequencies of values of a variable bucketed into ranges.
Histogram is similar to bar chat but the difference is it groups the values into continuous
ranges. Each bar in histogram represents the height of the number of values present in
that range.
R creates histogram using hist() function. This function takes a vector as an input and
uses some more parameters to plot histograms.
Syntax
The basic syntax for creating a histogram using R is −
hist(v,main,xlab,xlim,ylim,breaks,col,border)
Following is the description of the parameters used −
• v is a vector containing numeric values used in histogram.
• main indicates title of the chart.
• col is used to set color of the bars.
• border is used to set border color of each bar.
• xlab is used to give description of x-axis.
• xlim is used to specify the range of values on the x-axis.
• ylim is used to specify the range of values on the y-axis.
• breaks is used to mention the width of each bar.
Example
A simple histogram is created using input vector, label, col and border parameters.
The script given below will create and save the histogram in the current R working
directory.
# Create data for the graph.
v<-c(9,13,21,8,36,22,12,41,31,33,19)
# Give the chart file a name.
png(file = "[Link]")
# Create the histogram.
hist(v,xlab = "Weight",col = "yellow",border = "blue")
When we execute the above code, it produces the following result −
Output:
R - Scatterplots
Scatterplots show many points plotted in the Cartesian plane. Each point represents the
values of two variables. One variable is chosen in the horizontal axis and another in the
vertical axis.
Syntax
The basic syntax for creating scatterplot in R is −
Example
We use the data set "mtcars" available in the R environment to create a basic scatterplot.
Let's use the columns "wt" and "mpg" in mtcars.
print(head(input))
wt mpg
Mazda RX4 2.620 21.0
Mazda RX4 Wag 2.875 21.0
Datsun 710 2.320 22.8
Hornet 4 Drive 3.215 21.4
Hornet Sportabout 3.440 18.7
Valiant 3.460 18.1
Creating the Scatterplot
The below script will create a scatterplot graph for the relation between wt(weight) and
mpg(miles per gallon).
Syntax
The basic syntax for creating scatterplot matrices in R is −
pairs(formula, data)
Following is the description of the parameters used −
• data represents the data set from which the variables will be taken.
Example
Each variable is paired up with each of the remaining variable. A scatterplot is plotted for
each pair.
Attributes:
x the coordinates of points in the plot. Alternatively, a single plotting structure, function
or any R object with a plotmethod can be provided.
y the y coordinates of points in the plot, optional if x is an appropriate structure.
... Arguments to be passed to methods, such as graphical parameters (see par). Many
methods will accept the following arguments:
type
what type of plot should be drawn. Possible types are
• "p" for points,
• "l" for lines,
• "b" for both,
• "c" for the lines part alone of "b",
• "o" for both ‘overplotted’,
• "h" for ‘histogram’ like (or ‘high-density’) vertical lines,
• "s" for stair steps,
• "S" for other steps, see ‘Details’ below,
• "n" for no plotting.
All other types give a warning or an error; using, e.g., type = "punkte" being
equivalent to type = "p" for S compatibility. Note that some methods, e.g.
[Link], do not accept this.
main
an overall title for the plot
sub
a sub title for the plot
xlab
a title for the x axis
ylab
a title for the y axis
asp
the y/x aspect ratio
1) plot(iris$[Link], iris$[Link], pch=23, bg=c("red","green3","blue")
[unclass(iris$Species)], main="Iris Data")
Aim: Generate box plots for each of the numerical attributes. Identify the attribute
with the highest variance.
R - Boxplots
Boxplots are a measure of how well distributed is the data in a data set. It divides the data
set into three quartiles. This graph represents the minimum, maximum, median, first
quartile and third quartile in the data set. It is also useful in comparing the distribution of
data across data sets by drawing boxplots for each of them.
Syntax
The basic syntax to create a boxplot in R is −
Example
We use the data set "mtcars" available in the R environment to create a basic boxplot.
Let's look at the columns "mpg" and "cyl" in mtcars.
mpg cyl
Mazda RX4 21.0 6
Mazda RX4 Wag 21.0 6
Datsun 710 22.8 4
Hornet 4 Drive 21.4 6
Hornet Sportabout 18.7 8
Valiant 18.1 6
Creating the Boxplot
The below script will create a boxplot graph for the relation between mpg (miles per gallon)
and cyl (number of cylinders).
R - Vectors
Vectors are the most basic R data objects and there are six types of atomic vectors. They
are logical, integer, double, complex, character and raw.
Vector Creation
Single Element Vector
Even when you write just one value in R, it becomes a vector of length 1 and belongs to
one of the above vector types.
[1] 5 6 7 8 9 10 11 12 13
[1] 6.6 7.6 8.6 9.6 10.6 11.6 12.6
[1] 3.8 4.8 5.8 6.8 7.8 8.8 9.8 10.8
[1] 5.0 5.4 5.8 6.2 6.6 7.0 7.4 7.8 8.2 8.6 9.0
The non-character values are coerced to character type if one of the elements is a
character.
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.
[Link] <- v1+v2
print([Link])
# Vector subtraction.
[Link] <- v1-v2
print([Link])
# Vector multiplication.
[Link] <- v1*v2
print([Link])
# Vector division.
[Link] <- v1/v2
print([Link])
v1 <- c(3,8,4,5,0,11)
v2 <- c(4,11)
# V2 becomes c(4,11,4,11,4,11)
[Link] <- v1+v2
print([Link])
[Link] <- v1-v2
print([Link])
[1] 7 19 8 16 4 22
[1] -1 -3 0 -6 -4 0
[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"
R - Lists
Lists are the R objects which contain elements of different types like − numbers, strings,
vectors and another list inside it. A list can also contain a matrix or a function as its
elements. List is created using list() function.
Creating a List
Following is an example to create a list containing strings, numbers, vectors and a logical
values.
[[1]]
[1] "Red"
[[2]]
[1] "Green"
[[3]]
[1] 21 32 11
[[4]]
[1] TRUE
[[5]]
[1] 51.23
[[6]]
[1] 119.1
$`1st_Quarter`
[1] "Jan" "Feb" "Mar"
$A_Matrix
[,1] [,2] [,3]
[1,] 3 5 -2
[2,] 9 1 8
$A_Inner_list
$A_Inner_list[[1]]
[1] "green"
$A_Inner_list[[2]]
[1] 12.3
$`1st_Quarter`
[1] "Jan" "Feb" "Mar"
$A_Inner_list
$A_Inner_list[[1]]
[1] "green"
$A_Inner_list[[2]]
[1] 12.3
[,1] [,2] [,3]
[1,] 3 5 -2
[2,] 9 1 8
[[1]]
[1] "New element"
$<NA>
NULL
$`A Inner list`
[1] "updated element"
Merging Lists
You can merge many lists into one list by placing all the lists inside one list() function.
# 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)
[[1]]
[1] 1 2 3 4 5
[[1]]
[1] 10 11 12 13 14
[1] 1 2 3 4 5
[1] 10 11 12 13 14
[1] 11 13 15 17 19
R - Matrices
Matrices are the R objects in which the elements are arranged in a two-dimensional
rectangular layout. They contain elements of the same atomic types. Though we can
create a matrix containing only characters or only logical values, they are not of much use.
We use matrices containing numeric elements to be used in mathematical calculations.
Syntax:
The basic syntax for creating a matrix in R is −
Example
Create a matrix taking a vector of numbers as input.
[1] 5
[1] 13
col1 col2 col3
6 7 8
row1 row2 row3 row4
5 8 11 14
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.
An array is created using the array() function. It takes vectors as input and uses the values
in the dim parameter to create an array.
Example
The following example creates an array of two 3x3 matrices each with 3 rows and 3
columns.
,,1
,,2
, , Matrix1
, , Matrix2
Syntax
apply(x, margin, fun)
Example
We use the apply() function below to calculate the sum of the elements in the rows of an
array across all the matrices.
,,1
,,2
[1] 56 68 60
R - Data Frames
A data frame is a table or a two-dimensional array-like structure in which each column
contains values of one variable and each row contains one set of values from each
column.
[Link].emp_name [Link]
1 Rick 623.30
2 Dan 515.20
3 Michelle 611.00
4 Ryan 729.00
5 Gary 843.25
Extract the first two rows and then all columns
emp_name start_date
3 Michelle 2014-11-15
5 Gary 2015-03-27
Add Column
Just add the column vector using a new column name.
Add Row
To add more rows permanently to an existing data frame, we need to bring in the new
rows in the same structure as the existing data frame and use the rbind() function.
In the example below we create a data frame with new rows and merge it with the existing
data frame to create the final data frame.
Aim: Write R Program using ‘apply’ group of functions to create and apply
normalization function on each of the numeric variables/columns of iris dataset to
transform them into a value around 0 with z-score normalization.
Experiment No. 7 Date:
Aim:
a) Use R to apply linear regression to predict evaporation coefficient in terms of air
velocity using the data given below:
Aim:
a) Create an ARFF (Attribute-Relation File Format) file and read it in WEKA.
b) Explore the purpose of each button under the preprocess panel after loading
the ARFF file.
c) Also, try to interpret using a different ARFF file, weather. arff, provided with
WEKA.
Program:
Aim: Implement AI problem solving through Rule based forward chaining inference
using public domain software tool like CLIPS.
Experiment No. 15 Date: