Unlocking the Power of Vectors in R
What is a Vector in R?
Imagine you need to record the ages of five employees. Instead of creating five separate variables, you can store all the data in a single entity called a vector. A vector is the fundamental data structure in R that holds data of similar types.
Creating a Vector in R
To create a vector, you can use the c()
function, which combines multiple elements into a single vector. For instance, let’s create a vector named employees
with elements “Sabby”, “Cathy”, and “Lucy”.
employees <- c("Sabby", "Cathy", "Lucy")
Unpacking Vector Elements
Each element in a vector has a corresponding index number, starting from 1. You can access these elements using their index numbers. For example, if you have a vector languages
with elements “Swift”, “Java”, and “R”, you can access the first element using languages[1]
, which returns “Swift”.
languages <- c("Swift", "Java", "R")
print(languages[1]) # Output: [1] "Swift"
Modifying Vector Elements
Need to make changes to a vector element? Simply reassign a new value to the specific index. For instance, you can change the second element of a vector from “Repeat” to “Sleep” by assigning a new value.
actions <- c("Run", "Repeat", "Jump")
actions[2] <- "Sleep"
print(actions) # Output: [1] "Run" "Sleep" "Jump"
Working with Numeric Vectors
Creating a numeric vector is similar to creating a string vector. You can use the c()
function or the more efficient :
operator to create a sequence of numbers. For example, numbers <- 1:5
creates a vector with numerical values from 1 to 5.
numbers <- 1:5
print(numbers) # Output: [1] 1 2 3 4 5
Repeating Vectors
The rep()
function allows you to repeat elements of vectors. You can repeat the entire vector or each element individually. For instance, rep(numbers, times = 2)
repeats the entire vector two times, while rep(numbers, each = 2)
repeats each element two times.
numbers <- 1:5
print(rep(numbers, times = 2)) # Output: [1] 1 2 3 4 5 1 2 3 4 5
print(rep(numbers, each = 2)) # Output: [1] 1 1 2 2 3 3 4 4 5 5
Looping Through Vectors
Want to access all elements of a vector? Use a for
loop to iterate through each element. This is particularly useful when working with large datasets.
numbers <- 1:5
for (num in numbers) {
print(num)
}
# Output:
# [1] 1
# [1] 2
# [1] 3
# [1] 4
# [1] 5
Measuring Vector Length
Finally, you can use the length()
function to find the number of elements present inside a vector. This is useful when working with dynamic datasets.
numbers <- 1:5
print(length(numbers)) # Output: [1] 5