ZetCode

R vectorization

last modified November 19, 2026

Vectorization is the habit of applying an operation to a whole vector instead of to one element at a time. In R almost every arithmetic operator and many functions are vectorised: they accept a vector and return a result with one value per input value. This article shows element-wise arithmetic, the recycling rule that combines vectors of different lengths, vectorised mathematical functions, logical summaries, and the Vectorize wrapper for functions that only accept a single value.

Element-wise operations

An operation is element-wise when it pairs the first elements of its operands, then the second elements, and so on. The result has the same length as the input, and no loop is written. The next script adds five points to every score and divides every score by one hundred.

elementwise.R
scores <- c(72, 85, 90, 66, 78)
curved <- scores + 5
percent <- scores / 100
cat("scores:", scores, "\n")
cat("curved:", curved, "\n")
cat("percent:", percent, "\n")

The two operations produce new vectors of length five and leave scores unchanged. R never modifies the input of an arithmetic expression; the result is a separate object, which is then stored under a new name. The division also shows that the result is a double vector even though the input contains whole numbers.

$ Rscript elementwise.R
scores: 72 85 90 66 78 
curved: 77 90 95 71 83 
percent: 0.72 0.85 0.9 0.66 0.78 

Recycling

When two vectors have different lengths, R repeats the shorter one until it is long enough, a rule called recycling. A single number is recycled to every element, which is why scores + 5 worked above. The shorter vector is reused from the beginning, as the next script shows with two tax rates.

recycle.R
prices <- c(100, 200, 300, 400)
rates <- c(0.05, 0.10)
tax <- prices * rates
cat("tax:", tax, "\n")
cat("total:", prices + tax, "\n")

The first and third prices receive the five percent rate, and the second and fourth receive ten percent. R issues a warning when the longer length is not a multiple of the shorter one, because the last repetition is then only partly used. Such a warning almost always means that the two vectors were not meant to be combined, so treat it as an error rather than as a feature.

$ Rscript recycle.R
tax: 5 20 15 40 
total: 105 220 315 440 

Vectorised functions

Many mathematical functions are vectorised in the same way as the operators. sqrt, log, and exp take a vector and return a vector of the same length, applying the function to each element. Summary functions such as mean and sum also accept a vector, but they reduce it to a single value instead.

calculations.R
values <- c(2, 4, 9, 16, 25)
cat("sqrt:", sqrt(values), "\n")
cat("log:", round(log(values), 3), "\n")
cat("exp:", round(exp(c(0, 1, 2)), 3), "\n")

log is the natural logarithm, with base e, and exp is its inverse. round is vectorised too, so the call rounds every logarithm to three decimal places. Mixing vectorised and reducing functions in one expression is normal: mean(sqrt(values)) would first take the square roots and then average them.

$ Rscript calculations.R
sqrt: 1.414214 2 3 4 5 
log: 0.693 1.386 2.197 2.773 3.219 
exp: 1 2.718 7.389 

Logical vectors as summaries

Comparisons are vectorised as well, so a comparison of a vector with a number returns a logical vector with one value per element. Because TRUE counts as one and FALSE as zero, sum over such a vector counts the true values and mean returns their share. The functions all and any reduce the vector to a single logical answer.

conditions.R
scores <- c(72, 85, 60, 90, 55)
passed <- scores >= 70
cat("passed:", passed, "\n")
cat("count:", sum(passed), "\n")
cat("share:", mean(passed), "\n")
cat("all passed:", all(passed), "\n")
cat("any failed:", any(!passed), "\n")

Three of the five scores pass, so the count is three and the share is 0.6. all asks whether every element is true, and any asks whether at least one is; negating the logical vector first asks whether at least one score failed. This idiom replaces a loop with a counter in most data analysis code.

$ Rscript conditions.R
passed: TRUE TRUE FALSE TRUE FALSE 
count: 3 
share: 0.6 
all passed: FALSE 
any failed: TRUE 

Writing a vectorised function

A function written with if works on one value, because the condition of an if must have length one. The function Vectorize takes such a function and returns a new function that applies it to every element of a vector. The wrapper does not make the body faster; it only saves writing the loop.

wrapping.R
grade <- function(score) {
  if (score >= 90) {
    "A"
  } else if (score >= 80) {
    "B"
  } else {
    "C"
  }
}
scores <- c(95, 84, 61, 78)
grades <- Vectorize(grade)(scores)
cat("grades:", grades, "\n")

Vectorize(grade) returns a function, and the parentheses after it call that function with scores as its argument. The result is an ordinary character vector with one grade per score. For a function that already works on vectors, the wrapper is unnecessary; it exists for scalar logic such as this chain of conditions.

$ Rscript wrapping.R
grades: A B C C 

Why vectorization matters

Vectorised operations are implemented in C and run as a single call, while an explicit R loop runs the interpreter once per element. The difference is small for five scores and large for a column with a million rows. Vectorised code is also shorter and states the intent directly: scores + 5 says what happens, while a loop says how to make it happen.

The gain is not unlimited. An operation that needs the result of the previous element, such as a running total or a simulation, still needs a loop. For those cases R has the apply family, covered later in the series, and the performance article shows how to measure the difference instead of guessing. The rule of thumb is to use a vectorised expression whenever the elements are independent.

A complete example

The next script rescales the scores to a zero-to-hundred range. The formula subtracts the smallest value from every score, divides by the range, and multiplies by one hundred. The subtraction, the division, and the multiplication are all vectorised, and the three scalars are recycled.

normalize.R
scores <- c(72, 85, 90, 66, 78)
lowest <- min(scores)
highest <- max(scores)
normalized <- (scores - lowest) / (highest - lowest) * 100
cat("normalized:", round(normalized, 1), "\n")
cat("mean:", mean(normalized), "\n")

The lowest score becomes zero and the highest becomes one hundred, while the others keep their relative positions. The normalized mean is not fifty, because the original scores are not symmetric around their midpoint. The parentheses around the two subtractions are required: without them the division and the multiplication would bind to single values instead of to the whole differences.

$ Rscript normalize.R
normalized: 25 79.2 100 0 50 
mean: 50.83333 

Next steps

The random numbers article uses vectorised functions to draw thousands of values at once, and the vectors article explains how to build, index, and name the vectors that these operations consume. The apply-family article later in the series covers the cases where a loop is still the right tool.

Source

An Introduction to R: vector arithmetic

The R Language Definition: elementary arithmetic operations

R documentation: Vectorize

R documentation: arithmetic operators

In this article we have applied arithmetic to whole vectors, seen how R recycles a shorter operand, and used vectorised mathematical functions. We turned comparisons into counts and shares with sum, mean, all, and any, wrapped a scalar function with Vectorize, and rescaled a vector in one expression. The series continues with R random numbers.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all R Language tutorials.