AnyCompiler

Vectorized Operations

Because every value in R is already a vector, R's arithmetic and comparison operators are defined to work element-by-element across a whole vector in one expression. There is no map(), no list comprehension, no explicit loop needed for the common case — you just write the operation once, on the vector itself.

x <- c(1, 2, 3, 4, 5)
y <- c(10, 20, 30, 40, 50)
print(x + y)
print(x * 2)
print(x > 2)
Output
[1] 11 22 33 44 55
[1]  2  4  6  8 10
[1] FALSE FALSE  TRUE  TRUE  TRUE

x + y adds corresponding elements pairwise; x * 2 multiplies every element by the same scalar (itself a length-1 vector, recycled to match); x > 2 compares every element and returns a logical vector of the same length — which, as the next lesson shows, doubles as a ready-made selection mask.

Recycling

When two vectors in an operation have different lengths, R "recycles" the shorter one — repeating it from the start until it's as long as the longer one. This is deliberate and often exactly what you want (like x * 2 above), but when the longer length isn't an exact multiple of the shorter one, R warns you it might not be what you meant. This is a real warning, captured from a real run:

a <- c(1, 2, 3, 4, 5)
b <- c(1, 2)
print(a + b)
Output
[1] 2 4 4 6 6

stderr
Warning message:
In a + b : longer object length is not a multiple of shorter object length

R still computed an answer — b's two elements (1, 2) were repeated as (1, 2, 1, 2, 1) to match a's length of 5 — but since 5 isn't a multiple of 2, the leftover recycling is almost always a sign of a length mismatch you didn't intend, which is exactly what the warning is flagging. Next: indexing and subsetting — positive, negative, and logical indexing, named vectors, and a real error from mixing index types.

Practice exercise

Given prices <- c(10, 20, 30), print prices after a 10% discount (multiply the whole vector by 0.9) with no loop.