SyntaxStudy
Sign Up
R Atomic Vectors and Vector Operations
R Beginner 1 min read

Atomic Vectors and Vector Operations

Vectors are the fundamental data structure in R. An atomic vector is a one-dimensional, ordered collection of elements that all share the same type. You create vectors with the c() (combine) function, with range sequences using the colon operator (1:10), or with helper functions like seq() and rep(). Every scalar value in R is actually a vector of length one, which is why there is no separate scalar type. Arithmetic and logical operations on vectors in R are element-wise by default. Adding two vectors of equal length adds corresponding elements; applying a function like sqrt() or log() to a vector returns a vector of the same length. This vectorised approach eliminates the need for explicit loops in many situations and makes code both concise and fast since the underlying computations run in optimised C code. Subsetting a vector uses single-bracket indexing with 1-based positions (unlike the 0-based indexing of Python and C). You can subset with a numeric index, a logical vector of the same length, or by name if the vector has a names attribute. Negative indexing drops elements rather than selecting them, which is a powerful convenience when you want to exclude one or more positions.
Example
# Creating vectors
nums  <- c(4, 8, 15, 16, 23, 42)
words <- c("apple", "banana", "cherry")
flags <- c(TRUE, FALSE, TRUE, TRUE)

# Sequences and repetitions
seq1  <- 1:10                        # 1 2 3 ... 10
seq2  <- seq(0, 1, by = 0.25)        # 0.00 0.25 0.50 0.75 1.00
seq3  <- seq(2, 20, length.out = 5)  # 5 evenly spaced values
reps  <- rep(c(1, 2), times = 3)     # 1 2 1 2 1 2
reps2 <- rep(c(1, 2), each  = 3)     # 1 1 1 2 2 2

# Element-wise arithmetic
a <- c(1, 2, 3, 4)
b <- c(10, 20, 30, 40)
a + b       # 11 22 33 44
b - a       # 9 18 27 36
a * b       # 10 40 90 160
b / a       # 10 10 10 10
a ^ 2       # 1  4  9 16
sqrt(b)     # 3.16 4.47 5.48 6.32

# Logical operations (element-wise)
a > 2       # FALSE FALSE TRUE TRUE
a == 2      # FALSE TRUE  FALSE FALSE

# Subsetting
nums[1]        # 4   (1-based)
nums[c(1, 3)]  # 4 15
nums[-2]       # drop the 2nd element: 4 15 16 23 42
nums[nums > 15]  # 16 23 42  — logical subsetting

# Named vectors
ages <- c(Alice = 30, Bob = 25, Carol = 35)
ages["Bob"]    # 25
names(ages)    # "Alice" "Bob" "Carol"