R Vectors

A vector is the most basic data structure in R. It stores multiple values of the same type in a single, ordered container. Almost everything in R is built on vectors — even a single number like 42 is technically a vector of length 1.

What Is a Vector?

Single value (length 1):   42
                            │
                       [1] 42

Vector (length 5):    c(10, 20, 30, 40, 50)
                       │    │    │    │    │
Position:            [1]  [2]  [3]  [4]  [5]

Vectors are ordered: position 1 always comes before position 2. Every element in a vector must be the same data type.

Creating Vectors

# Numeric vector
scores <- c(85, 92, 78, 95, 60)

# Character vector
cities <- c("Delhi", "Mumbai", "Chennai", "Kolkata")

# Logical vector
results <- c(TRUE, FALSE, TRUE, TRUE)

# Integer vector
ranks <- c(1L, 2L, 3L, 4L, 5L)

# Sequence vector
nums <- 1:10          # 1 2 3 4 5 6 7 8 9 10
evens <- seq(2, 10, by = 2)   # 2 4 6 8 10

# Repeated values
zeros <- rep(0, 5)    # 0 0 0 0 0
rep_vec <- rep(c(1, 2), times = 3)  # 1 2 1 2 1 2

Accessing Vector Elements

scores <- c(85, 92, 78, 95, 60)

scores[1]          # 85   (first element)
scores[3]          # 78   (third element)
scores[c(1, 3)]    # 85 78 (first and third)
scores[2:4]        # 92 78 95 (second to fourth)
scores[-2]         # 85 78 95 60 (all except second)
Vector:   85   92   78   95   60
Index:    [1]  [2]  [3]  [4]  [5]

scores[3] → 78
scores[-2] → removes position 2: 85, 78, 95, 60

Named Vectors

monthly_sales <- c(Jan = 4500, Feb = 5200, Mar = 4800)

monthly_sales["Feb"]    # 5200
names(monthly_sales)    # "Jan" "Feb" "Mar"

Vector Operations (Vectorized)

prices <- c(100, 200, 150, 300)

prices * 1.18      # apply 18% tax: 118 236 177 354
prices + 50        # add 50 to each: 150 250 200 350
prices / 10        # divide each: 10 20 15 30
sum(prices)        # total: 750
mean(prices)       # average: 187.5
max(prices)        # highest: 300
min(prices)        # lowest: 100
length(prices)     # count: 4

Filtering a Vector

ages <- c(15, 22, 17, 30, 19, 25)

adults <- ages[ages >= 18]
print(adults)   # 22 30 19 25

# Count adults
sum(ages >= 18)   # 4

Modifying Vector Elements

scores <- c(85, 92, 78, 95, 60)
scores[3] <- 80    # change third element
print(scores)      # 85 92 80 95 60

scores[scores < 70] <- 70    # set all below 70 to 70
print(scores)      # 85 92 80 95 70

Type Coercion in Vectors

# Mixing types forces coercion to most flexible type
c(1, 2, "three")     # "1" "2" "three" (all become character)
c(TRUE, FALSE, 3)    # 1 0 3  (all become numeric)
c(1L, 2.5)           # 1.0 2.5 (all become numeric)

Useful Vector Functions

Function        Description
─────────────────────────────────────────────────────
length(x)       Number of elements
sort(x)         Sort in ascending order
rev(x)          Reverse order
unique(x)       Remove duplicates
table(x)        Count each value
which(x > 5)    Positions where condition is TRUE
append(x, v)    Add elements to vector

Vectors are the foundation of R. Data frames are made of vectors. Most statistical functions operate on vectors. Mastering vector creation, indexing, and vectorized operations makes every other R topic easier to learn.

Leave a Comment

Your email address will not be published. Required fields are marked *