x <- c(1, 2, 3) y <- c(10, 20) z <- x + y print(z)
In R, when you add two vectors of different lengths, the shorter one is recycled to match the longer one. Here, y = c(10, 20) is recycled to c(10, 20, 10). So, z = c(1+10, 2+20, 3+10) = c(11, 22, 13).
Vectors are fundamental because they provide a simple and consistent way to store sequences of data of the same type and allow efficient vectorized operations, which is core to R's design.
v <- c(5, 10, 15) print(v["2"])
In R, numeric vectors are indexed by numeric or logical values. Using a character string as an index without names causes an error.
The function c() combines values into a vector. Other options are either invalid syntax or incorrect function usage.
a <- c(2, 4, 6) b <- c(1, 3, 5) result <- a * b + 1 print(result)
Element-wise multiplication: (2*1, 4*3, 6*5) = (2, 12, 30). Adding 1 to each gives (3, 13, 31).
