Vector Operations
Part of the Fundamentals section of Coddy's R journey — lesson 59 of 78.
One of R's most powerful features is the ability to perform operations on entire vectors at once, without needing to loop through each element. This makes your code both cleaner and more efficient.
When you apply an arithmetic operator to a vector, R performs the operation on every element:
prices <- c(10, 25, 15, 30)
discounted <- prices * 0.9
print(discounted)Output:
[1] 9.0 22.5 13.5 27.0You can also perform operations between two vectors of the same length. R pairs up corresponding elements:
quantities <- c(2, 1, 4, 3)
prices <- c(10, 25, 15, 30)
totals <- quantities * prices
print(totals)Output:
[1] 20 25 60 90R provides useful built-in functions for common vector calculations like sum(), mean(), min(), and max():
scores <- c(85, 92, 78, 95, 88)
print(sum(scores))
print(mean(scores))
print(min(scores))
print(max(scores))Output:
[1] 438
[1] 87.6
[1] 78
[1] 95Challenge
EasyYou are provided with the following vectors:
hours_worked <- c(8, 7, 9, 6, 8)
hourly_rate <- c(15, 20, 18, 22, 17)Perform the following operations and print each result:
- Calculate the daily earnings for each day by multiplying
hours_workedbyhourly_rate(element-wise). Print this vector. - Apply a 10% bonus to all daily earnings (multiply by
1.1). Print the updated earnings vector. - Print the total earnings for the week using
sum() - Print the average daily earnings using
mean() - Print the highest single-day earnings using
max() - Print the lowest single-day earnings using
min()
Your output should be:
[1] 120 140 162 132 136
[1] 132.0 154.0 178.2 145.2 149.6
[1] 759
[1] 151.8
[1] 178.2
[1] 132Cheat sheet
R performs operations on entire vectors at once without needing loops.
Applying an arithmetic operator to a vector performs the operation on every element:
prices <- c(10, 25, 15, 30)
discounted <- prices * 0.9
print(discounted)
# [1] 9.0 22.5 13.5 27.0Operations between two vectors of the same length pair up corresponding elements:
quantities <- c(2, 1, 4, 3)
prices <- c(10, 25, 15, 30)
totals <- quantities * prices
print(totals)
# [1] 20 25 60 90Common built-in functions for vector calculations:
scores <- c(85, 92, 78, 95, 88)
sum(scores) # [1] 438
mean(scores) # [1] 87.6
min(scores) # [1] 78
max(scores) # [1] 95Try it yourself
# Given vectors
hours_worked <- c(8, 7, 9, 6, 8)
hourly_rate <- c(15, 20, 18, 22, 17)
# TODO: Write your code below
# 1. Calculate daily earnings (element-wise multiplication)
# 2. Apply 10% bonus to daily earnings
# 3. Print total earnings for the week using sum()
# 4. Print average daily earnings using mean()
# 5. Print highest single-day earnings using max()
# 6. Print lowest single-day earnings using min()This 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 22Variables 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