R — Vectors
What is a vector?
A vector is the most basic data structure in R — an ordered collection of values of the same type:
numbers <- c(1, 2, 3, 4, 5)
fruits <- c("apple", "banana", "cherry")
flags <- c(TRUE, FALSE, TRUE)
Even a single value is a vector of length 1:
x <- 42
length(x) # 1
Creating vectors
# c() — combine values
v1 <- c(1, 2, 3)
v2 <- c("a", "b", "c")
# : operator — sequences
v3 <- 1:10 # 1 2 3 4 5 6 7 8 9 10
v4 <- 10:1 # 10 9 8 7 6 5 4 3 2 1
# seq() — flexible sequences
seq(1, 10) # 1 2 3 4 5 6 7 8 9 10
seq(1, 10, by = 2) # 1 3 5 7 9
seq(1, 10, length.out = 5) # 1.0 3.25 5.50 7.75 10.00
seq(0, 1, by = 0.25) # 0.00 0.25 0.50 0.75 1.00
# rep() — repetition
rep(1, 5) # 1 1 1 1 1
rep(c(1, 2), 3) # 1 2 1 2 1 2
rep(c("a", "b"), each = 3) # a a a b b b
# Special vectors
numeric(5) # 0 0 0 0 0
character(3) # "" "" ""
logical(4) # FALSE FALSE FALSE FALSE
Accessing elements
x <- c(10, 20, 30, 40, 50)
# By position
x[1] # 10
x[5] # 50
# Multiple positions
x[c(1, 3, 5)] # 10 30 50
# Negative index — exclude
x[-1] # 20 30 40 50
x[c(-1, -3)] # 20 40 50
# Range
x[2:4] # 20 30 40
Subsetting with logical vectors
x <- c(10, 20, 30, 40, 50)
# Logical vector
x[c(TRUE, FALSE, TRUE, FALSE, TRUE)] # 10 30 50
# Condition — creates a logical vector
x > 25 # FALSE FALSE TRUE TRUE TRUE
x[x > 25] # 30 40 50
# Multiple conditions
x[x > 20 & x < 50] # 30 40
x[x < 20 | x > 40] # 10 50
# which() — get indices
which(x > 25) # 3 4 5
Named vectors
scores <- c(Alice = 90, Bob = 85, Charlie = 95)
scores["Alice"] # 90
scores[c("Alice", "Charlie")] # 90 95
names(scores) # "Alice" "Bob" "Charlie"
names(scores) <- c("A", "B", "C")
Modifying vectors
x <- c(1, 2, 3, 4, 5)
# Change elements
x[1] <- 10 # 10 2 3 4 5
x[c(2, 4)] <- 0 # 10 0 3 0 5
# Add elements
x <- c(x, 6) # append
x <- c(0, x) # prepend
# Remove elements
x <- x[-1] # remove first
x <- x[x != 3] # remove all 3s
# Replace with condition
x[x < 0] <- 0 # replace negatives with 0
Vector functions
x <- c(3, 1, 4, 1, 5, 9, 2, 6)
length(x) # 8
sum(x) # 31
mean(x) # 3.875
min(x) # 1
max(x) # 9
range(x) # 1 9
prod(x) # 6480
cumsum(x) # 3 4 8 9 14 23 25 31
cumprod(x) # 3 3 12 12 60 540 1080 6480
sort(x) # 1 1 2 3 4 5 6 9
sort(x, decreasing = TRUE) # 9 6 5 4 3 2 1 1
rev(x) # 6 2 9 5 1 4 1 3
# Unique values
unique(x) # 3 1 4 5 9 2 6
duplicated(x) # FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE
# Table of counts
table(x)
# x
# 1 2 3 4 5 6 9
# 2 1 1 1 1 1 1
Vectorized functions
Many functions work element-wise:
x <- c(1, 4, 9, 16, 25)
sqrt(x) # 1 2 3 4 5
log(x) # 0.00 1.39 2.20 2.77 3.22
log10(x) # 0.00 0.60 0.95 1.20 1.40
exp(x) # 2.72 54.60 8103.08 ...
abs(c(-1, 2, -3)) # 1 2 3
round(c(1.2, 2.5, 3.7), 0) # 1 3 4
ceiling(c(1.2, 2.5, 3.7)) # 2 3 4
floor(c(1.2, 2.5, 3.7)) # 1 2 3
Recycling
When vectors have different lengths, R repeats the shorter one:
c(1, 2, 3) + 10 # 11 12 13
c(1, 2, 3) * c(10, 20) # 10 40 30 — recycled!
Recycling is powerful but can cause subtle bugs. R warns when the lengths aren't multiples.
Combining vectors
a <- c(1, 2, 3)
b <- c(4, 5, 6)
c(a, b) # 1 2 3 4 5 6
append(a, b) # 1 2 3 4 5 6
append(a, b, after = 1) # 1 4 5 6 2 3
String vectors
words <- c("hello", "world", "foo", "bar")
nchar(words) # 5 5 3 3
toupper(words) # "HELLO" "WORLD" "FOO" "BAR"
tolower(words) # "hello" "world" "foo" "bar"
paste(words, collapse = " ") # "hello world foo bar"
strsplit("a,b,c", ",") # list with "a" "b" "c"
grep("o", words) # 1 2 — indices matching "o"
gsub("o", "0", words) # "hell0" "w0rld" "f00" "bar"
Common patterns
# Generate random data
rnorm(10) # 10 random normal values
runif(10) # 10 random uniform values (0-1)
sample(1:100, 10) # 10 random integers from 1-100
# Sequences for iteration
for (i in 1:10) {
print(i^2)
}
# Filtering
x <- c(10, 20, 30, 40, 50)
x[x > 25 & x < 45] # 30 40
Mini Practice
- Create a vector of the first 20 prime numbers
- Calculate the cumulative sum of 1:100
- Use logical subsetting to filter a vector to values between 10 and 50
- Create a named vector mapping five students to their grades
- Use
sample()to simulate rolling a die 100 times and count occurrences withtable()
Next: lists — collections of anything →
Related Topics
Frequently Asked Questions about Vectors
What is Vectors in R?
Vectors is a fundamental concept in R. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Vectors?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Vectors.
Why is Vectors important in R?
Vectors is essential for R development. Understanding this concept will help you write better code and solve real-world problems more effectively.