Reading — step 1 of 5
Learn
~1 min readEnvironments and Scoping
R is dynamic + interpreted, so loops are slow. Vectorized operations dispatch to compiled C/Fortran. The difference can be 100-1000x.
Slow:
result <- numeric(1000000)
for (i in 1:1000000) {
result[i] <- i * i
}
Fast:
result <- (1:1000000) ^ 2
Both produce the same vector. The vectorized version is ~50x faster.
Vectorized arithmetic — element-wise:
x <- c(1, 2, 3, 4)
y <- c(10, 20, 30, 40)
x + y # c(11, 22, 33, 44)
x * y # c(10, 40, 90, 160)
x > 2 # c(FALSE, FALSE, TRUE, TRUE) — also vectorized
Vectorized indexing:
v <- c(10, 20, 30, 40, 50)
v[v > 20] # c(30, 40, 50)
v[c(1, 3, 5)] # c(10, 30, 50)
v[-c(1, 2)] # exclude first two: c(30, 40, 50)
Logical operations propagate:
ages <- c(15, 30, 50, 70)
adults <- ages >= 18 & ages < 65 # c(FALSE, TRUE, TRUE, FALSE)
ages[adults] # c(30, 50)
Use ifelse for vectorized if:
x <- c(-3, -1, 0, 1, 3)
ifelse(x >= 0, "non-neg", "neg")
# c("neg", "neg", "non-neg", "non-neg", "non-neg")
Recycling rule — when vectors have different lengths, R recycles the shorter:
c(1, 2, 3, 4) + c(10, 20) # 11 22 13 24 — c(10,20) recycled
Watch out — sometimes intended, sometimes a bug.
Reduce for fold:
Reduce(`+`, 1:10) # 55
Reduce("+", 1:10, accumulate = TRUE)
# c(1, 3, 6, 10, 15, 21, 28, 36, 45, 55) — running totals
Vectorized string functions:
x <- c("apple", "banana", "cherry")
nchar(x) # c(5, 6, 6)
toupper(x) # c("APPLE", "BANANA", "CHERRY")
paste(x, collapse = ", ") # "apple, banana, cherry"
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…