Unlocking the Power of Vectors in R
What are Vectors in R?
Vectors are the fundamental building blocks of data structures in R, allowing you to store data of similar types in a single entity. Imagine you need to record the ages of 5 employees. Instead of creating 5 separate variables, you can create a vector to store all the ages in one place.
Creating a Vector in R
To create a vector in R, you can use the c()
function. For instance, you can create a vector named employees
with elements “Sabby”, “Cathy”, and “Lucy”. The c()
function combines these elements into a single vector.
employees <- c("Sabby", "Cathy", "Lucy")
Navigating Vector Elements
Each element in a vector is associated with a number, known as a vector index. You can access elements of a vector using this index number (1, 2, 3, and so on). For example, if you create a vector named languages
, you can access its elements using the index number. Remember, in R, the vector index always starts with 1.
Modifying Vector Elements
Need to change a vector element? Simply reassign a new value to the specific index. For instance, you can change the vector element at index 2 from “Repeat” to “Sleep” by assigning a new value.
languages <- c("Python", "Repeat", "Java")
languages[2] <- "Sleep"
print(languages)
Working with Numeric Vectors
Similar to strings, you can create a numeric vector using the c()
function. However, there’s a more efficient way to create a numeric sequence using the :
operator. This allows you to create a vector with numerical values in sequence.
Creating a Sequence of Numbers
The :
operator is a powerful tool for creating vectors with numerical values in sequence. For example, you can create a vector named numbers
with numerical values from 1 to 5.
numbers <- 1:5
print(numbers)
Repeating Vectors in R
The rep()
function allows you to repeat elements of vectors. You can repeat the whole vector or individual elements. For instance, you can create a numeric vector with elements 2, 4, 6 and repeat it twice.
numbers <- c(2, 4, 6)
repeated_numbers <- rep(numbers, 2)
print(repeated_numbers)
Looping Over a Vector
Need to access all elements of a vector? You can use a for
loop to iterate over each element of the vector. This is particularly useful when working with large datasets.
fruits <- c("Apple", "Banana", "Cherry")
for (fruit in fruits) {
print(fruit)
}
Finding the Length of a Vector
Finally, you can use the length()
function to find the number of elements present inside a vector. This is a handy tool for understanding the size of your dataset.
fruits <- c("Apple", "Banana", "Cherry")
print(length(fruits))