R
Beginner
1 min read
Vector Recycling, Lists, and Factors
Example
# Vector recycling
x <- 1:6
y <- c(10, 100) # length 2 recycled to match length 6
x + y # 11 102 13 104 15 106
# Recycling with a scalar (length 1 recycles perfectly)
x * 2 # 2 4 6 8 10 12
x - mean(x) # centre the vector
# Warning when lengths are not multiples
# c(1,2,3,4,5) + c(1,2) # warns: longer not multiple of shorter
# Lists: heterogeneous containers
person <- list(
name = "Diana",
age = 28,
scores = c(90, 85, 92),
active = TRUE
)
person[["name"]] # "Diana" — double bracket returns the element
person$age # 28 — dollar-sign shorthand
person["scores"] # a list containing the scores vector (single bracket)
person[["scores"]] # the numeric vector itself
# Modifying list elements
person$city <- "Paris"
person[["age"]] <- 29
# Nested lists
nested <- list(a = list(b = list(c = 42)))
nested$a$b$c # 42
# Factors
status <- factor(c("low", "med", "high", "med", "low"))
levels(status) # "high" "low" "med" (alphabetical by default)
nlevels(status) # 3
table(status) # frequency count
# Ordered factor
size <- ordered(c("S", "M", "L", "XL", "M"),
levels = c("S", "M", "L", "XL"))
size[1] < size[3] # TRUE (S < L)