EDS 221 Day 4 PM

Vectorized functions


August 13th, 2025

Vectorization


Vectorized functions and operators work on entire vectors at once, rather than element by element.

Using vectorization often improves code performance and clarity.

squares <- c(1, 4, 9, 16, 25)

# Loop
roots <- double(length(squares))
for (i in 1:length(roots)) {
  roots[i] <- sqrt(roots)
}

# Vectorized
roots <- sqrt(squares)

Functions and operators


Both functions and operators can be vectorized.

a <- 1:4
b <- 4:1

a + b
[1] 5 5 5 5
as.character(a)
[1] "1" "2" "3" "4"

Review


The round() function rounds numbers.

round(pi, digits = 2)
[1] 3.14

Consider this expression:

round(seq(0, 2, by = 1/2) * pi, digits = 2)

Using only pencil and paper, answer the following questions.

Tip

Solve sub-expressions first to build up to the complete solution.

  1. What will the output be?
  2. Which parameter is round() vectorized over?