Vectors
Build atomic vectors, apply vectorized ops, index, and recycle.
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
Data Frames
Create, inspect, filter, mutate, sort, aggregate, and merge data frames.
ggplot2
Build layered plots with geoms, facets, and themes using the grammar of graphics.
dplyr
Chain mutate, filter, group_by, summarise, and joins with the native pipe.
Statistics
Compute summaries, run t-tests, linear models, ANOVA, and use distributions.
Apply Family
Apply functions over arrays, lists, and groups with apply, lapply, sapply, tapply.
Data Import/Export
Read and write CSV, TSV, RDS, RData, and text files with base R.