0% found this document useful (0 votes)
13 views49 pages

Experiment

The document discusses different data types in R including numeric, integer, complex, character, and logical. It also covers operators in R like arithmetic, relational, and logical operators and provides examples of using each operator.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views49 pages

Experiment

The document discusses different data types in R including numeric, integer, complex, character, and logical. It also covers operators in R like arithmetic, relational, and logical operators and provides examples of using each operator.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 49

Experiment :- 1

 Explain different types of data types

Data Types

In programming, data type is an important concept.

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.

Basic Data Types

Basic data types in R can be divided into the following types:

 numeric - (10.5, 55, 787)


 integer - (1L, 55L, 100L, where the letter "L" declares this as an integer)
 complex - (9 + 3i, where "i" is the imaginary part)
 character (a.k.a. string) - ("k", "R is exciting", "FALSE", "11.5")
 logical (a.k.a. boolean) - (TRUE or FALSE)

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

 Explain different types of operators

Operators

Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

Example
10 + 5
Output:- [1] 15

R divides the operators in the following groups:

 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

− Subtracts second vector Live Demo


from the first
v <- c( 2,5.5,6)
t <- c(8, 3, 4)
print(v-t)
it produces the following
result −
[1] -6.0 2.5 2.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

Give the remainder of v <- c( 2,5.5,6)


%% the first vector with the t <- c(8, 3, 4)
print(v%%t)
second
it produces the following
result −
[1] 2.0 2.5 2.0

Live Demo

The result of division of v <- c( 2,5.5,6)


%/% first vector with second t <- c(8, 3, 4)
print(v%/%t)
(quotient)
it produces the following
result −
[1] 0 1 1
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.

Operator Description Example

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 Live Demo


element of the
first vector is 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
second vector.
[1] FALSE FALSE FALSE TRUE

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.

Operator Description Example


It is called
Element-wise
Logical AND
operator. It
combines each
element of the Live Demo
first vector with
the v <- c(3,1,TRUE,2+3i)
& t <- c(4,1,FALSE,2+3i)
corresponding
print(v&t)
element of the
it produces the following result −
second vector
[1] TRUE TRUE FALSE TRUE
and gives a
output TRUE if
both the
elements are
TRUE.

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.

! It is called Live Demo


Logical NOT
operator. Takes v <- c(3,0,TRUE,2+2i)
print(!v)
each element of
it produces the following result −
the vector and
[1] FALSE TRUE FALSE FALSE
gives the
opposite logical
value.

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. 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

These operators are used to assign values to vectors.


Operato
Description Example
r

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.

Operator Description Example

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

Explain vectors and lists

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

Output:- [1] "banana" "apple" "orange"

In this example, we create a vector that combines numerical values:

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

Result: [1] 1.5 2.5 3.5 4.5 5.5 6.5


[1] 1.5 2.5 3.5 4.5 5.5

[1] 1.5 2.5 3.5 4.5 5.5 6.5


In the example below, we create a vector of logical values

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)

sort(fruits) # Sort a string


sort(numbers) # Sort numbers

Output:- [1] "apple" "banana" "lemon" "mango" "orange"


[1] 2 3 5 7 13 20
Access Vectors
You can access the vector items by referring to its index number inside
brackets []. The first item has index 1, the second item has index 2, and so on:

Example
fruits <- c("banana", "apple", "orange")

# Access the first item (banana)


fruits[1]

Output:- [1] "banana"

You can also access multiple elements by referring to different index positions
with the c() function:

Example
fruits <- c("banana", "apple", "orange", "mango", "lemon")

# Access the first and third item (banana and orange)


fruits[c(1, 3)]

Output :- [1] "banana" "orange"

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)]

Output:- [1] "apple" "orange" "mango" "lemon

Change an Item
To change the value of a specific item, refer to the index number:

Example
fruits <- c("banana", "apple", "orange", "mango", "lemon")

# Change "banana" to "pear"


fruits[1] <- "pear"

# Print fruits
fruits

Output:-

[1] "pear" "apple" "orange" "mango" "lemon"

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_times <- rep(c(1,2,3), times = 3)

repeat_time

Output:- [1] 1 2 3 1 2 3 1 2 3

Example
Repeat each value independently:

repeat_indepent <- rep(c(1,2,3), times = c(5,2,1))

repeat_indepent

Output:- [1] 1 1 1 1 1 2 2 3

Generating Sequenced Vectors


One of the examples on top, showed you how to create a vector with numerical
values in a sequence with the : operator

Example
numbers <- 1:10

numbers

Output:- [1] 1 2 3 4 5 6 7 8 9 10

To make bigger or smaller steps in a sequence, use the seq() function:

Example
numbers <- seq(from = 0, to = 100, by = 20)

numbers

Output:-

Output:- [1] 0 20 40 60 80 100

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

# Create a list containing strings, numbers, vectors and a


logical
# values.
list_data <- list("Red", "Green", c(21,32,11), TRUE, 51.23,
119.1)
print(list_data)

When we execute the above code, it produces the following result −

[[1]]
[1] "Red"

[[2]]
[1] "Green"

[[3]]
[1] 21 32 11

[[4]]
[1] TRUE

[[5]]
[1] 51.23

[[6]]
[1] 119.1

Naming List Elements


The list elements can be given names and they can be accessed using these names.
Live Demo

# Create a list containing a vector, a matrix and a list.


list_data <- list(c("Jan","Feb","Mar"), matrix(c(3,9,5,1,-2,8),
nrow = 2),
list("green",12.3))

# Give names to the elements in the list.


names(list_data) <- c("1st Quarter", "A_Matrix", "A Inner list")

# Show the list.


print(list_data)

When we execute the above code, it produces the following result −

$`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

Accessing List Elements


Elements of the list can be accessed by the index of the element in the list. In case of named lists
it can also be accessed using the names.

We continue to use the list in the above example −

Live Demo

# Create a list containing a vector, a matrix and a list.


list_data <- list(c("Jan","Feb","Mar"), matrix(c(3,9,5,1,-2,8),
nrow = 2),
list("green",12.3))

# Give names to the elements in the list.


names(list_data) <- c("1st Quarter", "A_Matrix", "A Inner list")

# Access the first element of the list.


print(list_data[1])

# Access the thrid element. As it is also a list, all its


elements will be printed.
print(list_data[3])

# Access the list element using the name of the element.


print(list_data$A_Matrix)

When we execute the above code, it produces the following result −

$`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

Manipulating List Elements


We can add, delete and update list elements as shown below. We can add and delete elements
only at the end of a list. But we can update any element.

Live Demo

# Create a list containing a vector, a matrix and a list.


list_data <- list(c("Jan","Feb","Mar"), matrix(c(3,9,5,1,-2,8),
nrow = 2),
list("green",12.3))
# Give names to the elements in the list.
names(list_data) <- c("1st Quarter", "A_Matrix", "A Inner list")

# Add element at the end of the list.


list_data[4] <- "New element"
print(list_data[4])

# Remove the last element.


list_data[4] <- NULL

# Print the 4th Element.


print(list_data[4])

# Update the 3rd Element.


list_data[3] <- "updated element"
print(list_data[3])

When we execute the above code, it produces the following result −

[[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.

Live Demo

# Create two lists.


list1 <- list(1,2,3)
list2 <- list("Sun","Mon","Tue")

# Merge the two lists.


merged.list <- c(list1,list2)

# Print the merged list.


print(merged.list)
When we execute the above code, it produces the following result −

[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

[[4]]
[1] "Sun"

[[5]]
[1] "Mon"

[[6]]
[1] "Tue"

Converting List to Vector


A list can be converted to a vector so that the elements of the vector can be used for further
manipulation. All the arithmetic operations on vectors can be applied after the list is converted
into vectors. To do this conversion, we use the unlist() function. It takes the list as input and
produces a vector.
Live Demo

# 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)

When we execute the above code, it produces the following 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.

A Matrix is created using the matrix() function.

Syntax

The basic syntax for creating a matrix in R is −

matrix(data, nrow, ncol, byrow, dimnames)

Following is the description of the parameters used −

 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

Create a matrix taking a vector of numbers as input.

Live Demo

# Elements are arranged sequentially by row.


M <- matrix(c(3:14), nrow = 4, byrow = TRUE)
print(M)

# Elements are arranged sequentially by column.


N <- matrix(c(3:14), nrow = 4, byrow = FALSE)
print(N)

# Define the column and row names.


rownames = c("row1", "row2", "row3", "row4")
colnames = c("col1", "col2", "col3")

P <- matrix(c(3:14), nrow = 4, byrow = TRUE, dimnames =


list(rownames, colnames))
print(P)
When we execute the above code, it produces the following result −

[,1] [,2] [,3]


[1,] 3 4 5
[2,] 6 7 8
[3,] 9 10 11
[4,] 12 13 14
[,1] [,2] [,3]
[1,] 3 7 11
[2,] 4 8 12
[3,] 5 9 13
[4,] 6 10 14
col1 col2 col3
row1 3 4 5
row2 6 7 8
row3 9 10 11
row4 12 13 14

Accessing Elements of a Matrix


Elements of a matrix can be accessed by using the column and row index of the element. We
consider the matrix P above to find the specific elements below.

Live Demo

# Define the column and row names.


rownames = c("row1", "row2", "row3", "row4")
colnames = c("col1", "col2", "col3")

# Create the matrix.


P <- matrix(c(3:14), nrow = 4, byrow = TRUE, dimnames =
list(rownames, colnames))

# Access the element at 3rd column and 1st row.


print(P[1,3])

# Access the element at 2nd column and 4th row.


print(P[4,2])

# Access only the 2nd row.


print(P[2,])
# Access only the 3rd column.
print(P[,3])

When we execute the above code, it produces the following result −

[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.

Matrix Addition & Subtraction


Live Demo

# Create two 2x3 matrices.


matrix1 <- matrix(c(3, 9, -1, 4, 2, 6), nrow = 2)
print(matrix1)

matrix2 <- matrix(c(5, 2, 0, 9, 3, 4), nrow = 2)


print(matrix2)

# Add the matrices.


result <- matrix1 + matrix2
cat("Result of addition","\n")
print(result)

# Subtract the matrices


result <- matrix1 - matrix2
cat("Result of subtraction","\n")
print(result)

When we execute the above code, it produces the following result −

[,1] [,2] [,3]


[1,] 3 -1 2
[2,] 9 4 6
[,1] [,2] [,3]
[1,] 5 0 3
[2,] 2 9 4
Result of addition
[,1] [,2] [,3]
[1,] 8 -1 5
[2,] 11 13 10
Result of subtraction
[,1] [,2] [,3]
[1,] -2 -1 -1
[2,] 7 -5 2

Matrix Multiplication & Division


Live Demo

# Create two 2x3 matrices.


matrix1 <- matrix(c(3, 9, -1, 4, 2, 6), nrow = 2)
print(matrix1)

matrix2 <- matrix(c(5, 2, 0, 9, 3, 4), nrow = 2)


print(matrix2)

# Multiply the matrices.


result <- matrix1 * matrix2
cat("Result of multiplication","\n")
print(result)

# Divide the matrices


result <- matrix1 / matrix2
cat("Result of division","\n")
print(result)

When we execute the above code, it produces the following result −

[,1] [,2] [,3]


[1,] 3 -1 2
[2,] 9 4 6
[,1] [,2] [,3]
[1,] 5 0 3
[2,] 2 9 4
Result of multiplication
[,1] [,2] [,3]
[1,] 15 0 6
[2,] 18 36 24
Result of division
[,1] [,2] [,3]
[1,] 0.6 -Inf 0.6666667
[2,] 4.5 0.4444444 1.5000000
Experiment:-6

Explain Data frames

Data Frames are data displayed in a format as a table.

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.

Use the data.frame() function to create a data frame:

Example:

# Create a data frame


Data_Frame <- data.frame (
Training = c("Strength", "Stamina", "Other"),
Pulse = c(100, 150, 120),
Duration = c(60, 30, 45)
)

# Print the data frame


Data_Frame
Output:-
Training Pulse Duration
1 Strength 100 60
2 Stamina 150 30
3 Other 120 45

Summarize the Data


Use the summary() function to summarize the data 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

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 a new row


New_row_DF <- rbind(Data_Frame, c("Strength", 110, 110))

# Print the new row


New_row_D
Output:-
Training Pulse Duration
1 Strength 100 60
2 Stamina 150 30
3 Other 120 45
4 Strength 110 110

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)
)

# Add a new column


New_col_DF <- cbind(Data_Frame, Steps = c(1000, 6000, 2000))

# Print the new column


New_col_DF
Output:-
Training Pulse Duration Steps
1 Strength 100 60 1000
2 Stamina 150 30 6000
3 Other 120 45 2000

Remove Rows and Columns


Use the c() function to remove rows and 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)
)

# Remove the first row and column


Data_Frame_New <- Data_Frame[-c(1), -c(1)]

# Print the new data frame


Data_Frame_New
Output:-
Pulse Duration
2 150 30
3 120 45

Amount of Rows and Columns


Use the dim() function to find the amount of rows and 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

Data Frame Length


Use the length() function to find the number of columns in a Data Frame (similar to ncol()):
Example
Data_Frame <- data.frame (
Training = c("Strength", "Stamina", "Other"),
Pulse = c(100, 150, 120),
Duration = c(60, 30, 45)
)

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)
)

Data_Frame2 <- data.frame (


Training = c("Stamina", "Stamina", "Strength"),
Pulse = c(140, 150, 160),
Duration = c(30, 30, 20)
)

New_Data_Frame <- rbind(Data_Frame1, Data_Frame2)


New_Data_Frame
Output:-
Training Pulse Duration
1 Strength 100 60
2 Stamina 150 30
3 Other 120 45
4 Stamina 140 30
5 Stamina 150 30
6 Strength 160 20

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)
)

Data_Frame4 <- data.frame (


Steps = c(3000, 6000, 2000),
Calories = c(300, 400, 300)
)

New_Data_Frame1 <- cbind(Data_Frame3, Data_Frame4)


New_Data_Frame1

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")
}

Output:- [1] "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".

R uses curly brackets { } to define the scope in the code.

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")
}

Output:- [1] "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".

You can use as many else if statements as you want in R.

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")
}

Output:- [1] "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")
}

Output:- [1] "b is not greater than a"


Experiment:-8

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.

R has two loop commands:

 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.

If .. Else Combined with a While Loop


To demonstrate a practical example, let us say we play a game of Yahtzee!

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:-

[1] "No Yahtzee"


[1] "No Yahtzee"
[1] "No Yahtzee"
[1] "No Yahtzee"
[1] "No Yahtzee"
[1] "Yahtzee!"
For Loops
A for loop is used for iterating over a sequence:

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:

fruits <- list("apple", "banana", "cherry")

for (x in fruits) {
print(x)
}

Output:-

[1] "apple"
[1] "banana"
[1] "cherry"

Example

dice <- c(1, 2, 3, 4, 5, 6)

for (x in dice) {
print(x)
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6

If .. Else Combined with a For Loop


To demonstrate a practical example, let us say we play a game of Yahtzee!

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] "The dice number is 1 Not Yahtzee"


[1] "The dice number is 2 Not Yahtzee"
[1] "The dice number is 3 Not Yahtzee"
[1] "The dice number is 4 Not Yahtzee"
[1] "The dice number is 5 Not Yahtzee"
[1] "The dice number is 6 Yahtzee!"

[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":

fruits <- list("apple", "banana", "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":

fruits <- list("apple", "banana", "cherry")


for (x in fruits) {
if (x == "banana") {
next
}
print(x)
}

Output:- [1] "apple"


[1] "cherry"

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

You might also like