Vector Arithmetic & Recycling
Part of the Fundamentals section of Coddy's R journey — lesson 69 of 78.
When you perform arithmetic operations between two vectors of the same length, R applies the operation element by element:
a <- c(1, 2, 3)
b <- c(10, 20, 30)
print(a + b)Output:
[1] 11 22 33But what happens when the vectors have different lengths? R uses a behavior called recycling. The shorter vector is repeated to match the length of the longer one:
numbers <- c(1, 2, 3, 4, 5, 6)
multiplier <- c(10, 100)
print(numbers * multiplier)Output:
[1] 10 200 30 400 50 600Here, multiplier was recycled to become c(10, 100, 10, 100, 10, 100) before the multiplication. This is especially useful when operating with a single value:
prices <- c(10, 20, 30)
print(prices * 1.1)Output:
[1] 11 22 33The single value 1.1 is recycled to match the length of prices. Be cautious when the longer vector's length isn't a multiple of the shorter one, as R will still perform the operation but may produce a warning about partial recycling.
Challenge
EasyYou will receive two lines of input:
- A comma-separated list of numbers representing base values (e.g.,
10,20,30,40,50,60) - A comma-separated list of multipliers (e.g.,
2,5)
Using vector arithmetic and recycling:
- Create a numeric vector from the base values
- Create a numeric vector from the multipliers
- Multiply the base values by the multipliers (R will recycle the shorter vector)
- Print the result of the multiplication
- Add
100to each element of the original base values (single value recycling) - Print the result of the addition
- Subtract the multipliers vector from the base values vector
- Print the result of the subtraction
For example, if the inputs are:
5,10,15,20,25,30
3,7The output should be:
[1] 15 70 45 140 75 210
[1] 105 110 115 120 125 130
[1] 2 3 12 13 22 23Explanation:
- Multiplication: The multipliers
c(3, 7)are recycled toc(3, 7, 3, 7, 3, 7), resulting in5*3, 10*7, 15*3, 20*7, 25*3, 30*7 - Addition: The single value
100is recycled to add to each element - Subtraction: The multipliers are recycled again, resulting in
5-3, 10-7, 15-3, 20-7, 25-3, 30-7
Cheat sheet
When performing arithmetic operations between vectors of different lengths, R uses recycling - the shorter vector is repeated to match the length of the longer one:
numbers <- c(1, 2, 3, 4, 5, 6)
multiplier <- c(10, 100)
print(numbers * multiplier)Output:
[1] 10 200 30 400 50 600The multiplier vector is recycled to c(10, 100, 10, 100, 10, 100) before multiplication.
Single value recycling is particularly useful:
prices <- c(10, 20, 30)
print(prices * 1.1)Output:
[1] 11 22 33The value 1.1 is recycled to match the length of prices.
Note: R may produce a warning when the longer vector's length isn't a multiple of the shorter one.
Try it yourself
# Read input
con <- file("stdin", "r")
base_input <- suppressWarnings(readLines(con, n = 1))
multipliers_input <- suppressWarnings(readLines(con, n = 1))
close(con)
# Parse the comma-separated values into numeric vectors
base_values <- as.numeric(strsplit(base_input, ",")[[1]])
multipliers <- as.numeric(strsplit(multipliers_input, ",")[[1]])
# TODO: Write your code below
# 1. Multiply base_values by multipliers (recycling will happen automatically)
# 2. Print the multiplication result
# 3. Add 100 to each element of base_values
# 4. Print the addition result
# 5. Subtract multipliers from base_values
# 6. Print the subtraction resultThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators (AND, OR)Logical Operators Part 2 (NOT)Recap - Simple LogicVectorized Logic Part 1Vectorized Logic Part 27Bill Split Calculator
Welcome MessageGetting User Input13Vectors Advanced
Vector Slicing and IndexingLogical IndexingVector Arithmetic & RecyclingThe %in% Operator2Variables and Data Types
Numeric Data TypeInteger Data TypeCharacter Data TypeLogical Data TypeChecking Data TypesNaming ConventionsMissing Values: NARecap - Variable Creation8Loops
For LoopWhile LoopBreakNext (Continue)Recap - FactorialSequence Generation (seq, :)Nested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsInteger Division and ModuloAssignment OperatorsRecap - Simple MathComparison Operators6Basic IO
Print OutputCat for OutputOutput With VariablesReading Input with readline()Type Conversion BasicsRecap - Age CalculatorRecap - True or False9Functions
Declaring a FunctionFunction ArgumentsReturn ValuesRecap - Sigma FunctionRecap - Validation FunctionDefault Parameter Values