In the previous notebook we worked with creating object, which stores 1 value to an object. We are occasionally interested in storing several values to an object.
Let’s imagine that we would like to analyze the test scores of five students. We can create five variables:
student1 <- 90
student2 <- 85
student3 <- 86
student4 <- 92
student5 <- 93
and the compute the average by using the following code:
total <- student1 + student2 + student3 + student4 + student5
average <- total / 5
However, dataset in the real world can have many elements, and it is unrealistic to create variables for each individual element. Instead, we can create a vector that includes multiple values.
Vector is one of the most important concepts in R programming, and it can be created by using c()
function.
For example:
score <- c(90, 85, 86, 92, 93)
score
## [1] 90 85 86 92 93
The function mean()
can get the average value in the vector:
mean(score)
## [1] 89.2
We write: vector_name[number]
to access the element in the vector. For example:
# Acess the 1st element in the score vector
score[1]
## [1] 90
Instead of specifying 1 number, we can write number1:number2 inside [ ] to access multiple elements.
For example:
score[2:4]
## [1] 85 86 92
This will return a vector of elements from score[2]
to score[4]
.
We can also change 1 element in a vector in the original list instead of creating a new one by specifying
vector_name[number] <- element
For example:
score <- c(90, 85, 86, 92, 93)
score[1] <- 100
score
## [1] 100 85 86 92 93
We can add an element at the end of the vector through the append()
function, which can be written as:
append(vector_name, element)
For example.
score <- c(90, 85, 86, 92, 93)
score <- append(score, 0)
score
## [1] 90 85 86 92 93 0
We can get the length of vector through length()
function. For example,
number <- c(1, 2, 3)
length(number)
## [1] 3
Just like how we used c()
to create a vector, we can combine vectors by using the same function. For example:
a <- c(1,2,3)
b <- c(11,12,13)
vec <- c(a,b)
vec
## [1] 1 2 3 11 12 13
Vector is a very important concept in R programming and we will be frequently using the concept in the future labs.
©2021 by Daiki Tagami. All rights reserved.