Skip to content
R

Vectors

Build atomic vectors, apply vectorized ops, index, and recycle.

By EZ4Code Team
vectoratomic

Code

# Atomic vectors
nums  <- c(2, 4, 6, 8, 10)
chars <- c("a", "b", "c")
logi  <- c(TRUE, FALSE, TRUE)

# Types and length
print(class(nums))
print(length(nums))

# Vectorized arithmetic
print(nums * 2)
print(nums + c(1, 1, 1, 1, 1))
print(nums^2)

# Recycling
print(nums + c(1, 2))   # short vector recycled

# Indexing
print(nums[3])
print(nums[c(1, 4)])
print(nums[-1])           # exclude first
print(nums[nums > 4])     # logical

# Named vectors
scores <- c(math = 90, sci = 85, eng = 88)
print(scores["math"])
print(scores[scores > 86])

# Sequence and repetition
print(1:5)
print(seq(0, 1, by = 0.25))
print(seq(0, 1, length.out = 5))
print(rep("x", 3))
print(rep(1:2, each = 3))

# Missing values
x <- c(1, 2, NA, 4)
print(mean(x))
print(mean(x, na.rm = TRUE))
print(is.na(x))

Explanation

Vectors are R's fundamental data structure and nearly every operation is vectorized, applying element-by-element without loops. Indexing works by position, negative position, logical mask, or name, and short operands are recycled to match longer ones. NA propagates through arithmetic, so most summary functions accept na.rm = TRUE to skip missing values.

More R Snippets