R Programming Zero to Hero ๐๐๐
|
How to Download R?
Let's see the Basic syntax and code of R Programming...
We can also create new script for future…
Run script by ctrl + r.
Always save file as .R extension .
To run all lines of program …..
Let’s see about RStudio…
DATA TYPES
R Data Types:
Variables are the reserved memory
location to store values. As we create a variable
in our program, some space is reserved in memory.
In R, there are several
data types such as integer, string, etc. The operating system allocates memory
based on the data type of the variable and decides what can be stored in the
reserved memory.
|
Data type |
Example |
Description |
|
Logical |
True,
False |
It is a special data type for data with only two possible values
which can be construed as true/false. |
|
Numeric |
12,32,112,5432 |
Decimal value is called numeric in R, and it is the default
computational data type. |
|
Integer |
3L,
66L, 2346L |
Here, L tells R
to store the value as an integer, |
|
Complex |
Z=1+2i, t=7+3i |
A complex value in R is defined as the pure imaginary value i. |
|
Character |
'a',
'"good'", "TRUE",
'35.4' |
In R programming, a character is used to represent string values. We
convert objects into character values with the help ofas.character()
function. |
|
Raw |
|
A raw data type
is used to holds raw bytes. |
DATA
– Conversion : -
1) 3.Others to Complex:-
5) Others to Character:- It direct converts all data types in String form.
CONDITIONAL STATEMENT:-
EF –ELSE:-
NOTE:- 1) We can
use %in% to check component exist in vector or not.
2)
We can use else if also.
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.
Syntax
switch(expression,
case1, case2, case3....)
# Switch Statement
>
v1<-c(1,2,3,4,5)
>
option<-"mean"
> switch(option,
"mean"=
print(mean(v1)),"mode"=print(mod(v1)),"median"=print(median(v1)),print("invalid"));
Next Statement:
The next statement is used to skip any remaining statements
in the loop and continue executing. In simple words, a next statement is a
statement which skips the current iteration of a loop without terminating it.
When the next statement is encountered, the R parser skips further evaluation
and starts the next iteration of the loop.
This statement is mostly used with for loop and while loop.
Syntax:
Next
# Next
# ??? Skip the
current iteration.
v <-
LETTERS[1:6]
for ( i in v) {
if (i == "D") {
next
}
print(i)
}
Break statement:
In the R language, the break statement is used to break the
execution and for an immediate exit from the loop. In nested loops, break exits
from the innermost loop only and control transfer to the outer loop.
Syntax:
Break
Loops
in R
A loop
statement allows us to execute a statement or group of statements multiple
times.
Repeat
Loop
It
executes the same code again and again until a stop condition is met.
Syntax:
repeat
{
commands
if(condition)
{
break
}
}
While
Loop
In while loop, firstly the condition will be checked and
then after the body of the statement will execute. In this statement, the
condition will be checked n+1 time, rather than n times.
Syntax:
while (test_expression) {
statement
}
For Loop
In R, a for loop is a way to repeat a sequence of
instructions under certain conditions. It allows us to automate parts of our
code which need repetition. In simple words, a for loop is a repetition control
structure. It allows us to efficiently write the loop that needs to execute a
certain number of time.
Syntax:
for (value in vector) {
statements
}
#
Loops
#
Repeat Loop
x<-2
repeat{
x=x^2
print(x)
if(x>100)
break
}
# Whil
e loop
v
<- c("Hello","while loop")
cnt
<- 2
while
(cnt < 7) {
print(v)
cnt = cnt + 1
}
Functions in R
A set of statements which are organized together to perform
a specific task is known as a function. R provides a series of in-built
functions, and it allows the user to create their own functions. Functions are
used to perform tasks in the modular approach.
Functions are used to avoid repeating the same task and to
reduce complexity.
"An R function is created by using the keyword
function."
Syntax:
func_name <- function(arg_1, arg_2, ...) {
Function body
}
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.
Example
# 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))
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.
Example 1:
# Creating a function without an argument.
new.function <- function() {
for(i in 1:5) {
print(i^2)
}
}
#Calling of function
new.function()
Example 2:
# Creating a function with arguments.
new.function <- function(x,y,z) {
result <- x * y + z
print(result)
}
# Calling the function by position of arguments.
new.function(11,13,9)
# Calling the function by names of the arguments.
new.function(x = 2, y = 5, z = 3)
#
Similarly user can define their own
#
??? Create a function to print square of numbers in sequence.
new.function
<- function(a) {
for(i in 1:a) {
b <- i^2
print(b)
}
}
new.function(4)
new.function
<- function(a,b,c)
{
result <- a * b + c
print(result)
}
#
call by position.
new.function(5,3,11)
#
call by name.
new.function(a
= 11, b = 5, c =3)
#
Math :
abs(-3.666)
sqrt(4)# ??? abs(x) - Absolute value of x
sum(1,2,3,4)
k=c(3,3,2,1)
sum(k)
cos(35)
tan(34)
exp(100)
log(56)
#
??? Statistical functions :
mean(2,3,1,2,3,4)
median(2,3,1,2,3,4)
min(2,3,1,2,3,4)
max(2,3,1,2,3,4)
?quantile
quantile(c(2,3,1,2,3,4))
output:
>
m
[,1] [,2] [,3]
[1,] 11
12 13
[2,] 55
60 65
[3,] 66
72 78
>
length(m)
[1]
9
>
range(m)
[1]
11 78
>
rep(1,6)
[1]
1 1 1 1 1 1
>
sign(-1.11)
[1]
-1
>
sign(1.11)
[1]
1
>
sign(-31.11)
[1]
-1
>
sign(0)
[1]
0
tolower("DARSHAN")
toupper("darshAN")
m=c(5,2,3,2,4,3,2,4,2,1,3,2,3,5,3,2)
length(m)
unique(m)
floor(3.9)
ceiling(1.1)
round(1.55)
round(1.5)
Sys.Date()
Sys.time()
|
R
PROGRAMMING |
We can also create new script for future…
Run script by ctrl + r.
Always save file as .R extension .
To run all lines of program …..
Let’s see about RStudio…
|
Terminal & Console |
|
Global Variable |
|
Graphical Area |
|
Scripting Area |
Variables :- (Container for data)
Underscore and number at starting not allowed.
|
Assignment |
|
DATA TYPES |
R Data Types:
Variables are the reserved memory
location to store values. As we create a variable
in our program, some space is reserved in memory.
In R, there are several
data types such as integer, string, etc. The operating system allocates memory
based on the data type of the variable and decides what can be stored in the
reserved memory.
|
Data type |
Example |
Description |
|
Logical |
True,
False |
It is a special data type for data with only two possible values
which can be construed as true/false. |
|
Numeric |
12,32,112,5432 |
Decimal value is called numeric in R, and it is the default
computational data type. |
|
Integer |
3L,
66L, 2346L |
Here, L tells R
to store the value as an integer, |
|
Complex |
Z=1+2i, t=7+3i |
A complex value in R is defined as the pure imaginary value i. |
|
Character |
'a',
'"good'", "TRUE",
'35.4' |
In R programming, a character is used to represent string values. We
convert objects into character values with the help ofas.character()
function. |
|
Raw |
|
A raw data type
is used to holds raw bytes. |
DATA
– Conversion : -
1) From others to numeric data type
|
Char to numeric
not possible if it contains alphabet |
2) Others to Integer :- (same
as numeric)
3) Others to Complex:-
4) Others to Logical : -
|
It gives False Only if value is 0. |
5) Others to Character:-
It direct converts all data types in String form.
|
Operators |
EF –ELSE:-
|
Always start else just after the if statement line. |
NOTE:- 1) We can
use %in% to check component exist in vector or not.
2)
We can use else if also.
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.
Syntax
switch(expression,
case1, case2, case3....)
# Switch Statement
>
v1<-c(1,2,3,4,5)
>
option<-"mean"
> switch(option,
"mean"=
print(mean(v1)),"mode"=print(mod(v1)),"median"=print(median(v1)),print("invalid"));
Next Statement:
The next statement is used to skip any remaining statements
in the loop and continue executing. In simple words, a next statement is a
statement which skips the current iteration of a loop without terminating it.
When the next statement is encountered, the R parser skips further evaluation
and starts the next iteration of the loop.
This statement is mostly used with for loop and while loop.
Syntax:
Next
# Next
# ??? Skip the
current iteration.
v <-
LETTERS[1:6]
for ( i in v) {
if (i == "D") {
next
}
print(i)
}
Break statement:
In the R language, the break statement is used to break the
execution and for an immediate exit from the loop. In nested loops, break exits
from the innermost loop only and control transfer to the outer loop.
Syntax:
Break
Loops
in R
A loop
statement allows us to execute a statement or group of statements multiple
times.
Repeat
Loop
It
executes the same code again and again until a stop condition is met.
Syntax:
repeat
{
commands
if(condition)
{
break
}
}
While
Loop
In while loop, firstly the condition will be checked and
then after the body of the statement will execute. In this statement, the
condition will be checked n+1 time, rather than n times.
Syntax:
while (test_expression) {
statement
}
For Loop
In R, a for loop is a way to repeat a sequence of
instructions under certain conditions. It allows us to automate parts of our
code which need repetition. In simple words, a for loop is a repetition control
structure. It allows us to efficiently write the loop that needs to execute a
certain number of time.
Syntax:
for (value in vector) {
statements
}
#
Loops
#
Repeat Loop
x<-2
repeat{
x=x^2
print(x)
if(x>100)
break
}
#
While loop
v
<- c("Hello","while loop")
cnt
<- 2
while
(cnt < 7) {
print(v)
cnt = cnt + 1
}
#LETTERS
v
<- LETTERS[1:4]
for
( i in v) {
print(i)
}
Functions in R
A set of statements which are organized together to perform
a specific task is known as a function. R provides a series of in-built
functions, and it allows the user to create their own functions. Functions are
used to perform tasks in the modular approach.
Functions are used to avoid repeating the same task and to
reduce complexity.
"An R function is created by using the keyword
function."
Syntax:
func_name <- function(arg_1, arg_2, ...) {
Function body
}
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.
Example
# 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))
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.
Example 1:
# Creating a function without an argument.
new.function <- function() {
for(i in 1:5) {
print(i^2)
}
}
#Calling of function
new.function()
Example 2:
# Creating a function with arguments.
new.function <- function(x,y,z) {
result <- x * y + z
print(result)
}
# Calling the function by position of arguments.
new.function(11,13,9)
# Calling the function by names of the arguments.
new.function(x = 2, y = 5, z = 3)
#
Similarly user can define their own
#
??? Create a function to print square of numbers in sequence.
new.function
<- function(a) {
for(i in 1:a) {
b <- i^2
print(b)
}
}
new.function(4)
new.function
<- function(a,b,c)
{
result <- a * b + c
print(result)
}
#
call by position.
new.function(5,3,11)
#
call by name.
new.function(a
= 11, b = 5, c =3)
#
Math :
abs(-3.666)
sqrt(4)# ??? abs(x) - Absolute value of x
sum(1,2,3,4)
k=c(3,3,2,1)
sum(k)
cos(35)
tan(34)
exp(100)
log(56)
#
??? Statistical functions :
mean(2,3,1,2,3,4)
median(2,3,1,2,3,4)
min(2,3,1,2,3,4)
max(2,3,1,2,3,4)
?quantile
quantile(c(2,3,1,2,3,4))
output:
>
m
[,1] [,2] [,3]
[1,] 11
12 13
[2,] 55
60 65
[3,] 66
72 78
>
length(m)
[1]
9
>
range(m)
[1]
11 78
>
rep(1,6)
[1]
1 1 1 1 1 1
>
sign(-1.11)
[1]
-1
>
sign(1.11)
[1]
1
>
sign(-31.11)
[1]
-1
>
sign(0)
[1]
0
tolower("DARSHAN")
toupper("darshAN")
m=c(5,2,3,2,4,3,2,4,2,1,3,2,3,5,3,2)
length(m)
unique(m)
floor(3.9)
ceiling(1.1)
round(1.55)
round(1.5)
Sys.Date()
Sys.time()
How To Take INPUT in R:-
R Data
Structures:
Data structures are very
important to understand. Data structure are the objects which we will manipulate
in our day-to-day basis in R. We can say that everything in R is an object.
R has many data structures, which include:
1.
Vector
2.
List
3.
Array
4.
Matrices
5.
Data Frame
6.
Factors
Vectors
A vector is the basic data structure in R, or we can say
vectors are the most basic R data objects. "A vector is a collection of
elements which is most commonly of mode character, integer, logical or
numeric"
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.
Syntax: a<-c(1,2,3,4)
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.
We
can create a list with the help of list(). Syntax: list<-list( a,
2.5,”hello”)
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
R, an array is created with the help of array()
function. This function takes a vector as an input and uses the value in
the dim parameter to create an array.
|
e.g. a <- array(c('green','yellow'),dim
= c(3,3,2)) |
Matrices
A matrix is an R object in which the elements are arranged in a two-dimensional rectangular layout.
In the matrix, elements of the same atomic types are contained. For mathematical calculation, this can use a matrix containing the numeric element. A matrix
is created with the help of the matrix()
function in R.
Syntax
The basic syntax
of creating a matrix is as follows:
1. matrix(data,
nrow, ncol, by_row, dim_name) data: input vector which becomes data element of matrix nrow and ncol: number of rows and coumns
by_row:
logical value. If true then input vector elements arranged by rows else by
columns. Dim_name: name assigned to rows and columns.
|
e.g. M = matrix( c('a','a','b','c','b','a'), nrow = 2, ncol = 3, byrow = TRUE) |
Factors
These are also data objects that are used to categorize
the data and store it as levels. Factors can store both strings and integers.
Columns have a limited number of unique values so that factors are very useful
in columns. It is very useful in data analysis for statistical modeling.
Factors are
created with the help of factor() function
by taking a vector as an input parameter.
E.g.
# Create a vector. apple_colors <-
c('green','green','yellow','red','red','red','green')
# Create a factor object. factor_apple <- factor(apple_colors)
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.
# 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)
)
E.g
|
# 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) ) |
Types of Data Visualizations
Some of the various types of visualizations offered by R are:
Bar Plot
There are two types of bar plots- horizontal and vertical which represent data points as horizontal or vertical bars of certain lengths proportional to the value of the data item. They are generally used for continuous and categorical variable plotting. By setting the horiz parameter to true and false, we can get horizontal and vertical bar plots respectively.
Histogram
A histogram is like a bar chart as it uses bars of varying height to represent data distribution. However, in a histogram values are grouped into consecutive intervals called bins. In a Histogram, continuous values are grouped and displayed in these bins whose size can be varied.
Box Plot
The statistical summary of the given data is presented graphically using a boxplot. A boxplot depicts information like the minimum and maximum data point, the median value, first and third quartile, and interquartile range.
Scatter Plot
A scatter plot is composed of many points on a Cartesian plane. Each point denotes the value taken by two parameters and helps us easily identify the relationship between them.
Heat Map
Heatmap is defined as a graphical representation of data using colors to visualize the value of the matrix. heatmap() function is used to plot heatmap.
Syntax: heatmap(data)
Parameters: data: It represent matrix data, such as values of rows and columns
Return: This function draws a heatmap.
Map visualization in R
Here we are using maps package to visualize and display geographical maps using an R programming language.
install.packages("maps")Line Graph visualization in R
A line chart is a graph that connects a series of points by drawing line segments between them. These points are ordered in one of their coordinate (usually the x-coordinate) value. Line charts are usually used in identifying the trends in data.
The plot() function in R is used to create the line graph.
Syntax
The basic syntax to create a line chart in R is −
plot(v,type,col,xlab,ylab)
ALSO SHARE THIS BLOG WITH YOUR FREINDS.....☺☺
AND ALSO COMMENT YOUR IDEAS AND PROBLEMS.
Comments
Post a Comment