Vectors
Vectors are one of the most basic and important data structures in R. A vector is an ordered collection of values of the same data type, such as numbers, characters, or logical (TRUE/FALSE) values.
In statistics and data science, vectors are commonly used to store data observations, variables, or results of calculations.
One-dimensional: Vectors have length but no rows or columns.
Homogeneous: All elements must be the same data type.
Ordered: Each element has a specific position (index).
Indexed starting at 1: R uses 1-based indexing (not 0).
The most common way to create a vector is using the c() (combine) function.
scores <- c(88, 92, 79, 85)
# Character vector
names <- c("Alex", "Jordan", "Taylor")
# Logical vector
passed <- c(TRUE, TRUE, FALSE, TRUE)
Use length() to find how many elements are in a vector.
You can access elements using square brackets [ ].
scores[2:4] # Elements 2 through 4
scores[-1] # All elements except the first
One of R’s strengths is that operations are vectorized, meaning they automatically apply to every element in a vector.
scores * 1.1
Vectors are the foundation of statistical analysis in R.
median(scores)
sd(scores)
summary(scores)
favstats(scores)
If you mix data types in a vector, R will coerce all elements to the most flexible type.
mixed
Logical vectors are often used to filter data.
❌ Trying to store different data types in one vector
❌ Forgetting that indexing starts at 1
❌ Confusing vectors with data frames or matrices
Almost everything in R is built on vectors:
Columns in data frames are vectors
Statistical models operate on vectors
Many R functions expect vector input