R provides several built-in data structures designed to store, organise, and analyse data effectively. These structures use basic data types such as numeric, integer, character, and logical. For anyone learning R for analytics, statistics, or data science, a strong understanding of these structures is essential.
The five primary data structures in R are:
- Atomic Vector
- List
- Matrix
- Data Frame
- Factor
Among these, vectors are the most fundamental and frequently used. They serve as the building blocks of many other structures, and mastering them makes the rest of R much easier to understand.
What is a Vector in R?
A vector is a one-dimensional sequence of elements, where all elements must belong to the same data type. Examples include numeric vectors, character vectors, and logical vectors. Many higher-level structures, such as matrices, arrays, and data frames, are created using vectors.
Ways to Create a Vector in R
R offers multiple ways to create vectors. The most commonly used methods are:
1. Using the C ( ) Function
The C ( ) (combine) function is the simplest and most flexible method for creating vectors.
my_vec1 <- c(1L, 2L, 3L) # we craeted vector function using C() function
print(my_vec1)
Output:
[1] 1 2 3
2. Using the Colon Operator :
The colon operator quickly generates ordered sequences of integers.
my_vec2 <- 1:3
print(my_vec2)
Output:
[1] 1 2 3
3. Using the Seq ( ) Function
The Seq ( ) function lets you specify the start value, end value, and step size.
my_vec3 <- seq(from = 1, to = 3, by = 1)
print(my_vec3)
Output:
[1] 1 2 3
Internal Type of Vectors
Even when vectors appear identical in output, they may have different internal data types such as integer, numeric, character, or logical. One important rule in R is:
A vector can store only one type of data.
If elements of different types are combined, R automatically converts them to a common type.
Example:
c(1, "R", TRUE)
This becomes a character vector.
Importance of Vectors in R
Vectors are at the core of almost every operation in R. They are used in mathematical calculations, data filtering, statistical functions, and as the foundation for columns in data frames. Their structure makes it possible to perform vectorized operations, which allow R to process entire datasets efficiently without looping manually.
In real-world data analysis, vectors help represent data such as ages, temperatures, IDs, scores, and logical conditions. When combined with indexing, vectors make filtering, subsetting, and transformation extremely powerful. A strong command of vectors sets the stage for mastering data frames, matrices, and even advanced libraries like dplyr and ggplot2.