Experiment
Experiment
Data Types
Variables can store data of different types, and different types can do different things.
In R, variables do not need to be declared with any particular type, and can even change type
after they have been set:
Example
my_var <- 30 # my_var is type of numeric
my_var <- "Sally" # my_var is now of type character (aka string)
Output:-
[1] "Sally"
R has a variety of data types and object classes. You will learn much more about these as you continue
to get to know R.
We can use the class() function to check the data type of a variable:
Example
# numeric
x <- 10.5
class(x)
# integer
x <- 1000L
class(x)
# complex
x <- 9i + 3
class(x)
# character/string
x <- "R is exciting"
class(x)
# logical/boolean
x <- TRUE
class(x)
Output:-
[1] "numeric"
[1] "integer"
[1] "complex"
[1] "character"
[1] "logical"
Experiment :-2
Operators
In the example below, we use the + operator to add together two values:
Example
10 + 5
Output:- [1] 15
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.
Operato
Description Example
r
Live Demo
v <- c( 2,5.5,6)
+ Adds two vectors t <- c(8, 3, 4)
print(v+t)
it produces the following
result −
[1] 10.0 8.5 10.0
Live Demo
v <- c( 2,5.5,6)
* Multiplies both vectors t <- c(8, 3, 4)
print(v*t)
it produces the following
result −
[1] 16.0 16.5 24.0
Live Demo
v <- c( 2,5.5,6)
t <- c(8, 3, 4)
Divide the first vector print(v/t)
/
with the second When we execute the
above code, it produces the
following result −
[1] 0.250000 1.833333
1.500000
Live Demo
Live Demo
v <- c( 2,5.5,6)
The first vector raised t <- c(8, 3, 4)
^ to the exponent of print(v^t)
second vector it produces the following
result −
[1] 256.000 166.375
1296.000
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.
Checks if each
Live Demo
element of the
first vector is v <- c(2,5.5,6,9)
> greater than the t <- c(8,2.5,14,9)
corresponding print(v>t)
element of the it produces the following result −
second vector. [1] FALSE TRUE FALSE FALSE
Checks if each
Live Demo
element of the
first vector is v <- c(2,5.5,6,9)
< less than the t <- c(8,2.5,14,9)
corresponding print(v < t)
element of the it produces the following result −
second vector. [1] TRUE FALSE TRUE FALSE
Checks if each
element of the Live Demo
first vector is
less than or v <- c(2,5.5,6,9)
<= t <- c(8,2.5,14,9)
equal to the
print(v<=t)
corresponding
it produces the following result −
element of the
[1] TRUE FALSE TRUE TRUE
second vector.
Checks if each
element of the Live Demo
first vector is
greater than or v <- c(2,5.5,6,9)
>= t <- c(8,2.5,14,9)
equal to the
print(v>=t)
corresponding
it produces the following result −
element of the
[1] FALSE TRUE FALSE TRUE
second vector.
Checks if each
Live Demo
element of the
first vector is v <- c(2,5.5,6,9)
!= unequal to the t <- c(8,2.5,14,9)
corresponding print(v!=t)
element of the it produces the following result −
second vector. [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.
It is called
Element-wise
Logical OR
operator. It
combines each
element of the Live Demo
first vector with
the v <- c(3,0,TRUE,2+2i)
| t <- c(4,0,FALSE,2+3i)
corresponding
print(v|t)
element of the
it produces the following result −
second vector
[1] TRUE FALSE TRUE TRUE
and gives a
output TRUE if
one the
elements is
TRUE.
The logical operator && and || considers only the first element of the vectors and give a vector of
single element as output.
Called
Logical
AND
operator. Live Demo
Takes first
element of v <- c(3,0,TRUE,2+2i)
&& t <- c(1,3,TRUE,2+3i)
both the
print(v&&t)
vectors and
it produces the following result −
gives the
[1] TRUE
TRUE only
if both are
TRUE.
Called
Logical OR
operator.
Live Demo
Takes first
element of v <- c(0,0,TRUE,2+2i)
|| both the t <- c(0,3,TRUE,2+3i)
vectors and print(v||t)
gives the it produces the following result −
TRUE if one [1] FALSE
of them is
TRUE.
Assignment Operators
Live Demo
v1 <- c(3,1,TRUE,2+3i)
v2 <<- c(3,1,TRUE,2+3i)
<− v3 = c(3,1,TRUE,2+3i)
or Called Left print(v1)
= Assignment print(v2)
or 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
Live Demo
c(3,1,TRUE,2+3i) -> v1
c(3,1,TRUE,2+3i) ->> v2
-> Called Right
print(v1)
or Assignment 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.
Colon
operator. It Live Demo
creates the
: series of v <- 2:8
print(v)
numbers in
it produces the following result −
sequence for
a vector. [1] 2 3 4 5 6 7 8
Live Demo
This
operator is v1 <- 8
used to v2 <- 12
t <- 1:10
%in% identify if an print(v1 %in% t)
element print(v2 %in% t)
belongs to a it produces the following result −
vector.
[1] TRUE
[1] FALSE
Live Demo
This
M = matrix( c(2,6,5,1,10,4), nrow = 2,ncol = 3,byrow = TRUE)
operator is
t = M %*% t(M)
used to print(t)
%*%
multiply a it produces the following result −
matrix with
[,1] [,2]
its transpose.
[1,] 65 82
[2,] 82 117
Experiment:-3
Vectors
A vector is simply a list of items that are of the same type.
To combine the list of items to a vector, use the c() function and separate the items
by a comma.
In the example below, we create a vector variable called fruits, that combine
strings:
Example
# Vector of strings
fruits <- c("banana", "apple", "orange")
# Print fruits
fruits
Example
# Vector of numerical values
numbers <- c(1, 2, 3)
# Print numbers
numbers
Output:- [1] 1 2 3
To create a vector with numerical values in a sequence, use the : operator:
Example
# Vector with numerical values in a sequence
numbers <- 1:10
numbers
Output:- [1] 1 2 3 4 5 6 7 8 9 10
You can also create numerical values with decimals in a sequence, but note that
if the last element does not belong to the sequence, it is not used:
Example
# Vector with numerical decimals in a sequence
numbers1 <- 1.5:6.5
numbers1
# Vector with numerical decimals in a sequence where the last element is not used
numbers2 <- 1.5:6.3
numbers2
Example
# Vector of logical values
log_values <- c(TRUE, FALSE, TRUE, FALSE)
log_values
Output:- [1] TRUE FALSE TRUE FALSE
Vector Length
To find out how many items a vector has, use the length() function:
Example
fruits <- c("banana", "apple", "orange")
length(fruits)
Output:- [1] 3
Sort a Vector
To sort items in a vector alphabetically or numerically, use the sort() function:
Example
fruits <- c("banana", "apple", "orange", "mango", "lemon")
numbers <- c(13, 3, 5, 7, 20, 2)
Example
fruits <- c("banana", "apple", "orange")
You can also access multiple elements by referring to different index positions
with the c() function:
Example
fruits <- c("banana", "apple", "orange", "mango", "lemon")
You can also use negative index numbers to access all items except the ones
specified:
Example
fruits <- c("banana", "apple", "orange", "mango", "lemon")
# Access all items except for the first item
fruits[c(-1)]
Change an Item
To change the value of a specific item, refer to the index number:
Example
fruits <- c("banana", "apple", "orange", "mango", "lemon")
# Print fruits
fruits
Output:-
Repeat Vectors
To repeat vectors, use the rep() function:
Example
Repeat each value:
repeat_each <- rep(c(1,2,3), each = 3)
repeat_each
Output:- [1] 1 1 1 2 2 2 3 3 3
Example
Repeat the sequence of the vector
repeat_time
Output:- [1] 1 2 3 1 2 3 1 2 3
Example
Repeat each value independently:
repeat_indepent
Output:- [1] 1 1 1 1 1 2 2 3
Example
numbers <- 1:10
numbers
Output:- [1] 1 2 3 4 5 6 7 8 9 10
Example
numbers <- seq(from = 0, to = 100, by = 20)
numbers
Output:-
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.
Live Demo
[[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
Live Demo
$`1st_Quarter`
[1] "Jan" "Feb" "Mar"
$A_Inner_list
$A_Inner_list[[1]]
[1] "green"
$A_Inner_list[[2]]
[1] 12.3
Live Demo
[[1]]
[1] "New element"
$<NA>
NULL
Merging Lists
You can merge many lists into one list by placing all the lists inside one list() function.
Live Demo
[[1]]
[1] 1
[[2]]
[1] 2
[[3]]
[1] 3
[[4]]
[1] "Sun"
[[5]]
[1] "Mon"
[[6]]
[1] "Tue"
# Create lists.
list1 <- list(1:5)
print(list1)
list2 <-list(10:14)
print(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
Experiment:-4
Explain Array
Experiment:-5
Explain Matrix
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
data is the input vector which becomes the data elements of the matrix.
nrow is the number of rows to be created.
ncol is the number of columns to be created.
byrow is a logical clue. If TRUE then the input vector elements are arranged by row.
dimname is the names assigned to the rows and columns.
Example
Live Demo
Live Demo
[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.
Data Frames can have different types of data inside it. While the first column
can be character, the second and third can be numeric or logical. However, each
column should have the same type of data.
Example:
Data_Frame
summary(Data_Frame)
Output:-
Training Pulse Duration
1 Strength 100 60
2 Stamina 150 30
3 Other 120 45
Training Pulse Duration
Other :1 Min. :100.0 Min. :30.0
Stamina :1 1st Qu.:110.0 1st Qu.:37.5
Strength:1 Median :120.0 Median :45.0
Mean :123.3 Mean :45.0
3rd Qu.:135.0 3rd Qu.:52.5
Max. :150.0 Max.
Access Items
We can use single brackets [ ], double brackets [[ ]] or $ to access columns from a data frame:
Example
Data_Frame <- data.frame (
Training = c("Strength", "Stamina", "Other"),
Pulse = c(100, 150, 120),
Duration = c(60, 30, 45)
)
Data_Frame[1]
Data_Frame[["Training"]]
Data_Frame$Training
Output:-
Training
1 Strength
2 Stamina
3 Other
[1] Strength Stamina Other
Levels: Other Stamina Strength
[1] Strength Stamina Other
Levels: Other Stamina Strength
Add Rows
Use the bind() function to add new rows in a Data Frame:
Example
Data_Frame <- data.frame (
Training = c("Strength", "Stamina", "Other"),
Pulse = c(100, 150, 120),
Duration = c(60, 30, 45)
)
Add Columns
Use the cbind() function to add new columns in a Data Frame:
Example
Data_Frame <- data.frame (
Training = c("Strength", "Stamina", "Other"),
Pulse = c(100, 150, 120),
Duration = c(60, 30, 45)
)
dim(Data_Frame)
Output:-
[1] 3 3
You can also use the ncol() function to find the number of columns and nrow() to find the
number of rows:
Example
Data_Frame <- data.frame (
Training = c("Strength", "Stamina", "Other"),
Pulse = c(100, 150, 120),
Duration = c(60, 30, 45)
)
ncol(Data_Frame)
nrow(Data_Frame)
Output:-
[1] 3
[1] 3
length(Data_Frame)
Output:-
[1] 3
Combining Data Frames
Use the rbind() function to combine two or more data frames in R vertically:
Example
Data_Frame1 <- data.frame (
Training = c("Strength", "Stamina", "Other"),
Pulse = c(100, 150, 120),
Duration = c(60, 30, 45)
)
And use the cbind() function to combine two or more data frames in R horizontally:
Example
Data_Frame3 <- data.frame (
Training = c("Strength", "Stamina", "Other"),
Pulse = c(100, 150, 120),
Duration = c(60, 30, 45)
)
Output:-
Training Pulse Duration Steps Calories
1 Strength 100 60 3000 300
2 Stamina 150 30 6000 400
3 Other 120 45 2000
Experiment:-7
Explain Conditionals Statements
The if Statement
An "if statement" is written with the if keyword, and it is used to specify a block
of code to be executed if a condition is TRUE:
Example
a <- 33
b <- 200
if (b > a) {
print("b is greater than a")
}
In this example we use two variables, a and b, which are used as a part of the if
statement to test whether b is greater than a. As a is 33, and b is 200, we know
that 200 is greater than 33, and so we print to screen that "b is greater than a".
Else If
The else if keyword is R's way of saying "if the previous conditions were not true,
then try this condition":
Example
a <- 33
b <- 33
if (b > a) {
print("b is greater than a")
} else if (a == b) {
print ("a and b are equal")
}
In this example a is equal to b, so the first condition is not true, but the else
if condition is true, so we print to screen that "a and b are equal".
If Else
The else keyword catches anything which isn't caught by the preceding
conditions:
Example
a <- 200
b <- 33
if (b > a) {
print("b is greater than a")
} else if (a == b) {
print("a and b are equal")
} else {
print("a is greater than b")
}
In this example, a is greater than b, so the first condition is not true, also
the else if condition is not true, so we go to the else condition and print to screen
that "a is greater than b".
You can also use else without else if:
Example
a <- 200
b <- 33
if (b > a) {
print("b is greater than a")
} else {
print("b is not greater than a")
}
Explain Loops
Loops
Loops can execute a block of code as long as a specified condition is reached.
Loops are handy because they save time, reduce errors, and they make code
more readable.
while loops
for loops
R While Loops
With the while loop we can execute a set of statements as long as a condition is
TRUE:
Example
Print i as long as i is less than 6:
i <- 1
while (i < 6) {
print(i)
i <- i + 1
}
Output:-
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
In the example above, the loop will continue to produce numbers ranging from
1 to 5. The loop will stop at 6 because 6 < 6 is FALSE.
The while loop requires relevant variables to be ready, in this example we need
to define an indexing variable, i, which we set to 1.
Example
Print "Yahtzee!" If the dice number is 6:
dice <- 1
while (dice <= 6) {
if (dice < 6) {
print("No Yahtzee")
} else {
print("Yahtzee!")
}
dice <- dice + 1
}
Output:-
Example
for (x in 1:10) {
print(x)
Output:-
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10
This is less like the for keyword in other programming languages, and works
more like an iterator method as found in other object-orientated programming
languages.
With the for loop we can execute a set of statements, once for each item in a
vector, array, list, etc..
Example
Print every item in a list:
for (x in fruits) {
print(x)
}
Output:-
[1] "apple"
[1] "banana"
[1] "cherry"
Example
for (x in dice) {
print(x)
}
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
Example
Print "Yahtzee!" If the dice number is 6:
dice <- 1:6
for(x in dice) {
if (x == 6) {
print(paste("The dice number is", x, "Yahtzee!"))
} else {
print(paste("The dice number is", x, "Not Yahtzee"))
}
}
Output:-
[1] 6
Experiment:-9
Explain Break and Next
Break
With the break statement, we can stop the loop even if the while condition is
TRUE:
Example
Exit the loop if i is equal to 4.
i <- 1
while (i < 6) {
print(i)
i <- i + 1
if (i == 4) {
break
}
}
Output:- [1] 1
[1] 2
[1] 3.
Break
With the break statement, we can stop the loop before it has looped through all
the items:
Example
Stop the loop at "cherry":
for (x in fruits) {
if (x == "cherry") {
break
}
print(x)
}
Output:-
[1] "apple"
[1] "banana"
Next
With the next statement, we can skip an iteration without terminating the loop:
Example
Skip the value of 3:
i <- 0
while (i < 6) {
i <- i + 1
if (i == 3) {
next
}
print(i)
}
Output:-
[1] 1
[1] 2
[1] 4
[1] 5
[1] 6
Next
With the next statement, we can skip an iteration without terminating the loop:
Example
Skip "banana":
O u t p u t : -
T o d e m o n s t r a t e a p r a c t i c a l e x a m p l e , l e t u s s a y w e p l a y a g a m e o f Y a h t z e e !
E x a m
p l e
P r i n t “ Y a h t z e e ! ” I f t h e d i c e n u m b e r i s 6 :
D i c e < - 1 : 6
F o r ( x i n d i c e ) {
I f ( x = = 6 ) {
P r i n t ( p a s t e ( “ T h e d i c e n u m b e r i s ” , x , “ Y a h t z e e ! ” ) )
} e l s e {
P r i n t ( p a s t e ( “ T h e d i c e n u m b e r i s ” , x , “ N o t Y a h t z e e ” ) )
CSS JAVASCRI
}
PT SQL PYTHO
N JAVA