Unit IV Big Dataanalytics
Unit IV Big Dataanalytics
loops, functions
R overview:
This programming language was named R, based on the first letter of first name
of the two R authors (Robert Gentleman and Ross Ihaka)
R allows integration with the procedures written in the C, C++, .Net, Python or
FORTRAN languages for efficiency.
Due to its expressive syntax and easy-to-use interface, it has grown in popularity
in recent years.
1
This not only shows the increasing interest in R as a programming language, but
also of the fields like Data Science and Machine Learning where R is commonly
used.
R code that you write on one platform can easily be ported to another without any
issues. Cross-platform interoperability is an important feature to have in today’s
computing world.
Features of R :
1
The CRAN (The Comprehensive R Archive Network) package repository features
has more than 8270 available packages.
R is platform-independent, so you can use it on any operating system
1. Go to [Link]
2. Under “Download and Install R”, click on the “Windows” link.
3. Under “Subdirectories”, click on the “base” link.
4. On the next page, you should see a link saying something like “Download R 3.4.3
for Windows” (or R X.X.X, where X.X.X gives the version of R, eg. R 3.4.3). Click
on this link.
5. You may be asked if you want to save or run a file “[Link]”. Choose
“Save” and save the file on the Desktop. Then double-click on the icon for the file to
run it.
6. You will be asked what language to install it in - choose English.
7. The R Setup Wizard will appear in a window. Click “Next” at the bottom of the R
Setup wizard window.
8. The next page says “Information” at the top. Click “Next” again.
9. The next page says “Information” at the top. Click “Next” again.
10. The next page says “Select Destination Location” at the top. By default, it will
suggest to install R in “C:\Program Files” on your computer.
11. Click “Next” at the bottom of the R Setup wizard window.
12. The next page says “Select components” at the top. Click “Next” again.
13. The next page says “Startup options” at the top. Click “Next” again.
14. The next page says “Select start menu folder” at the top. Click “Next” again.
15. The next page says “Select additional tasks” at the top. Click “Next” again.
16. R should now be installed. This will take about a minute. When R has finished, you
will see “Completing the R for Windows Setup Wizard” appear. Click “Finish”.
17. To start R, you can either follow step 18, or 19:
18. Check if there is an “R” icon on the desktop of the computer that you are using. If
so, double-click on the “R” icon to start R. If you cannot find an “R” icon, try step
19 instead.
19. Click on the “Start” button at the bottom left of your computer screen, and then
choose “All programs”, and start R by selecting “R” (or R X.X.X, where X.X.X gives
the version of R, eg. R 3.4.3) from the menu of programs.
20. The R console (a rectangle) should pop up:
1
How to install R / R Studio:
For Windows users, R Studio is available for Windows Vista and above versions.
1. Go to [Link]
2. In ‘Installers for Supported Platforms’ section, choose and click the R Studio
installer based on your operating system. The download should begin as soon as
you click.
3. Click Next..Next..Finish.
4. Download Complete.
5. To Start R Studio, click on its desktop icon or use ‘search windows’ to access the
program. It looks like this:
1
Let’s quickly understand the interface of R Studio:
1. R Console: This area shows the output of code you run. Also, you can directly
write codes in console. Code entered directly in R console cannot be traced later.
This is where R script comes to use.
2. R Script: As the name suggest, here you get space to write codes. To run those
codes, simply select the line(s) of code and press Ctrl + Enter. Alternatively, you
can click on little ‘Run’ button location at top right corner of R Script.
3. R environment: This space displays the set of external elements added. This
includes data set, variables, vectors, functions etc. To check if data has been
loaded properly in R, always look at this area.
4. Graphical Output: This space display the graphs created during exploratory
data analysis. Not just graphs, you could select packages, seek help
with embedded R’s official documentation.
Most data handling tasks can be performed in 2 ways: Using R packages and R
base functions. To install a package, simply type:
[Link]("package name")
R - Basic Syntax:
You will type R commands into the R console in order to carry out analyses in R.
In the R console you will see:
>
This is the R prompt. We type the commands needed for a particular task after this
prompt..
Once you have started R, you can start typing in commands, and the results
will be calculated immediately, for example:
Ex: > 2*3
[1] 6
> 10-3
[1] 7
Variables in R
Variables are used to store data, whose value can be changed according to our
need. Unique name given to variable (function and objects as well) is identifier.
1. Identifiers can be a combination of letters, digits, period (.) and underscore (_).
2. It must start with a letter or a period. If it starts with a period, it cannot be followed
by a digit.
3. Reserved words in R cannot be used as identifiers.
Valid identifiers in R
Invalid identifiers in R
All variables (scalars, vectors, matrices, etc.) created by R are called objects. In R, we
assign values to variables using an arrow and equals to operators.
For example, we can assign the value 2*3 to the variable x using the
command:
EX: > x <- 2*3
OR
> x=2*3
OR
> 2*3->x
To view the contents of any R object, just type its name, and the contents of
that R object will be displayed:
Ex: >x
1
[1] 6
OR
>print(x)
Comments
Comments are like helping text in your R program and they are ignored by the
interpreter while executing your actual program. Single comment is written using # in
the beginning of the statement as follows −
Constants in R
Constants, as the name suggests, are entities whose value cannot be altered. Basic
types of constant are numeric constants and character constants.
Numeric Constants
> typeof(5)
[1] "double"
> typeof(5L)
[1] "integer"
> typeof(5i)
[1] "complex"
> 0xff
[1] 255
> 0XF + 1
1
[1] 16
Character Constants
Character constants can be represented using either single quotes (') or double quotes
(") as delimiters.
> 'example'
[1] "example"
> typeof("5")
[1] "character"
Built-in Constants
Some of the built-in constants defined in R along with their values is shown below.
> LETTERS
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S"
[20] "T" "U" "V" "W" "X" "Y" "Z"
> letters
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
[20] "t" "u" "v" "w" "x" "y" "z"
> pi
[1] 3.141593
> [Link]
[1] "January" "February" "March" "April" "May" "June"
[7] "July" "August" "September" "October" "November" "December"
> [Link]
[1] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
1
> print("Hello World!")
[1] "Hello World!"
> # Quotes can be suppressed in the output
> print("Hello World!", quote = FALSE)
[1] Hello World!
> # If there are more than 1 item, we can concatenate using paste()
> print(paste("How","are","you?"))
[1] "How are you?"
In this program, we have used the built-in function print() to print the
string Hello World!
The quotes are printed by default. To avoid this we can pass the argument quote
= FALSE.
If there are more than one item, we can use the paste() or cat() function to
concatenate the strings together.
print(paste("Hi,", [Link], "next year you will be", [Link]+1, "years old."))
Output
1
R Reserved Words
Reserved words in R programming are a set of words that have special meaning and
cannot be used as an identifier (variable name, function name etc.).
Reserved words in R
This list can be viewed by typing help(reserved) or ?reserved at the R command prompt
as follows.
> ?reserved
R - Data Types:
There are several basic data types in R which are of frequent occurrence in coding R
calculations and programs. 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.
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.
1
Data Example Verify
Type
v <- TRUE
[1] "logical"
v <- 23.5
[1] "numeric"
v <- 2L
[1] "integer"
v <- 2+5i
Complex 3 + 2i print(class(v))
[1] "complex"
v <- "TRUE"
Character 'a' , '"good", "TRUE", '23.4'
print(class(v))
1
[1] "character"
v <- charToRaw("Hello")
"Hello" is stored as 48 65 6c 6c print(class(v))
Raw
6f
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.
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)
[[1]]
1
[1] 2 5 3
[[2]]
[1] 21.3
[[3]]
function (x) .Primitive("sin")
Matrices
# Create a matrix.
print(M)
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.
# Create an array.
print(a)
,,1
1
,,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() [Link] 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.
1
height = c(152, 171.5, 165),
weight = c(81,93, 78),
Age = c(42,38,26)
)
print(BMI)
R-Operators:
Types of Operators
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.
1
Operator Description Example
v <- c( 2,5.5,6)
t <- c(8, 3, 4)
+ Adds two vectors
print(v+t)
v <- c( 2,5.5,6)
Subtracts second t <- c(8, 3, 4)
− vector from the
print(v-t)
first
it produces the following result −
v <- c( 2,5.5,6)
t <- c(8, 3, 4)
Multiplies both
*
vectors print(v*t)
v <- c( 2,5.5,6)
t <- c(8, 3, 4)
Divide the first
/ vector with the print(v/t)
second
When we execute the above code, it produces
the following result −
1
v <- c( 2,5.5,6)
Give the
t <- c(8, 3, 4)
remainder of the
%%
first vector with print(v%%t)
the second
it produces the following result −
v <- c( 2,5.5,6)
The result of
division of first t <- c(8, 3, 4)
%/% vector with
second print(v%/%t)
(quotient) it produces the following result −
[1] 0 1 1
v <- c( 2,5.5,6)
The first vector
t <- c(8, 3, 4)
raised to the
^
exponent of print(v^t)
second vector
it produces the following result −
Relational Operators
1
second vector. print(v>t)
v <- c(2,5.5,6,9)
Checks if each element of the
t <- c(8,2.5,14,9)
first vector is less than the
<
corresponding element of the print(v < t)
second vector.
it produces the following result −
v <- c(2,5.5,6,9)
Checks if each element of the
t <- c(8,2.5,14,9)
first vector is equal to the
==
corresponding element of the print(v == t)
second vector.
it produces the following result −
v <- c(2,5.5,6,9)
Checks if each element of the
t <- c(8,2.5,14,9)
first vector is less than or equal
<=
to the corresponding element print(v<=t)
of the second vector.
it produces the following result −
1
[1] FALSE TRUE FALSE TRUE
v <- c(2,5.5,6,9)
Checks if each element of the
t <- c(8,2.5,14,9)
first vector is unequal to the
!=
corresponding element of the print(v!=t)
second vector.
it produces the following result −
Logical Operators
It is called Element-wise
Logical AND operator. It v <- c(3,1,TRUE,2+3i)
combines each element of the
t <- c(4,1,FALSE,2+3i)
first vector with the
&
corresponding element of the print(v&t)
second vector and gives a
output TRUE if both the it produces the following result −
elements are TRUE. [1] TRUE TRUE FALSE TRUE
It is called Element-wise
Logical OR operator. It v <- c(3,0,TRUE,2+2i)
combines each element of the
| t <- c(4,0,FALSE,2+3i)
first vector with the
corresponding element of the print(v|t)
second vector and gives a
output TRUE if one the it produces the following result −
1
elements is TRUE. [1] TRUE FALSE TRUE TRUE
The logical operator && and || considers only the first element of the vectors and
give a vector of single element as output.
v <- c(3,0,TRUE,2+2i)
Called Logical AND operator.
Takes first element of both t <- c(1,3,TRUE,2+3i)
&&
the vectors and gives the print(v&&t)
TRUE only if both are TRUE.
it produces the following result −
[1] TRUE
v <- c(0,0,TRUE,2+2i)
Called Logical OR operator.
Takes first element of both t <- c(0,3,TRUE,2+3i)
|| the vectors and gives the
TRUE if one of them is print(v||t)
TRUE. it produces the following result −
[1] FALSE
Assignment Operators
1
Operator Description Example
v1 <- c(3,1,TRUE,2+3i)
v2 <<- c(3,1,TRUE,2+3i)
<− v3 = c(3,1,TRUE,2+3i)
or print(v1)
= Called Left Assignment
print(v2)
or print(v3)
<<−
it produces the following result −
c(3,1,TRUE,2+3i) -> v1
c(3,1,TRUE,2+3i) ->> v2
->
print(v1)
or Called Right Assignment
print(v2)
->>
it produces the following result −
Miscellaneous Operators
These operators are used to for specific purpose and not general mathematical or
logical computation.
: Colon operator.
It creates the v <- 2:8
1
series of print(v)
numbers in
sequence for a it produces the following result −
vector.
[1] 2 3 4 5 6 7 8
v1 <- 8
v2 <- 12
This operator is
used to identify if t <- 1:10
%in% an element print(v1 %in% t)
belongs to a
vector. print(v2 %in% t)
[1] TRUE
[1] FALSE
[,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.
1
R provides the following types of decision making statements.
If Statement:
Syntax
if(boolean_expression) {
// statement(s) will execute if the boolean expression is true.
}
If the Boolean expression evaluates to be true, then the block of code inside the if
statement will be executed. If Boolean expression evaluates to be false, then the first set
of code after the end of the if statement (after the closing curly brace) will be executed.
Flow Diagram
1
Example
x <- 30L
if([Link](x)) {
print("X is an Integer")
When the above code is compiled and executed, it produces the following result −
If...Else Statement
An if statement can be followed by an optional else statement which executes when the
boolean expression is false.
Syntax
if(boolean_expression) {
// statement(s) will execute if the boolean expression is true.
} else {
// statement(s) will execute if the boolean expression is false.
}
If the Boolean expression evaluates to be true, then the if block of code will be
executed, otherwise else block of code will be executed.
Flow Diagram
1
Example
x <- c("what","is","truth")
if("Truth" %in% x) {
print("Truth is found")
} else {
print("Truth is not found")
}
When the above code is compiled and executed, it produces the following
result −
Syntax
if(boolean_expression 1) {
// Executes when the boolean expression 1 is true.
} else if( boolean_expression 2) {
// Executes when the boolean expression 2 is true.
} else if( boolean_expression 3) {
// Executes when the boolean expression 3 is true.
} else {
// executes when none of the above condition is true.
}
1
Example
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 −
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.
Example
x <- switch( 3,
"first",
1
"second",
"third",
"fourth"
)
print(x)