Bird
Raised Fist0
R Programmingprogramming~10 mins

Vector arithmetic (element-wise) in R Programming - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Vector arithmetic (element-wise)
Start with two vectors
↓
Add/subtract/multiply/divide elements
↓
Perform operation element-wise
↓
Result: new vector with element-wise results
↓
End
This flow shows how two vectors are combined by doing the operation on each pair of elements one by one.
Execution Sample
R Programming
a <- c(2, 4, 6)
b <- c(1, 3, 5)
c <- a + b
print(c)
Adds two vectors element by element and prints the result.
Execution Table
StepOperationa[i]b[i]Result[i]Explanation
1Add2132 + 1 = 3
2Add4374 + 3 = 7
3Add65116 + 5 = 11
4Print result--3 7 11Final vector after element-wise addition
💡 All elements processed; vector addition complete.
Variable Tracker
VariableStartAfter 1After 2After 3Final
ac(2,4,6)246c(2,4,6)
bc(1,3,5)135c(1,3,5)
cempty3711c(3,7,11)
Key Moments - 2 Insights
Why does R add vectors element by element instead of summing all elements?
R performs vector arithmetic element-wise by design, as shown in execution_table rows 1-3, where each pair of elements is added separately to produce a new vector.
What happens if vectors have different lengths?
If vectors differ in length, R recycles the shorter vector elements to match the longer one. This is not shown here but is important to avoid unexpected results.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of c[2] after the second step?
A3
B4
C7
D11
💡 Hint
Check the 'Result[i]' column in row 2 of execution_table.
At which step does the vector c get fully created?
AStep 3
BStep 1
CStep 4
DStep 2
💡 Hint
Look at the 'Operation' column and see when the full vector is printed.
If vector b was shorter, how would the addition behave?
AIt would cause an error
BIt would recycle elements of b to match a
CIt would ignore extra elements in a
DIt would add only the first element of b to all elements of a
💡 Hint
Recall the key_moments explanation about vector length differences.
Concept Snapshot
Vector arithmetic in R works element-wise.
Use +, -, *, / operators between vectors.
Each element in one vector combines with the corresponding element in the other.
If vectors differ in length, shorter vector elements recycle.
Result is a new vector of the same length as the longest input.
Full Transcript
This example shows how R adds two vectors element by element. Starting with vectors a and b, each element pair is added to form a new vector c. The execution table traces each addition step, showing the values combined and the result. The variable tracker shows how c builds up over time. Beginners often wonder why R does element-wise addition instead of summing all elements; this is because vector arithmetic is designed to work element-wise. Also, if vectors have different lengths, R recycles the shorter vector's elements to match the longer one. The visual quiz tests understanding of the step-by-step addition and behavior with different vector lengths.

Practice

(1/5)
1.

What happens when you add two vectors of the same length in R, like c(1, 2, 3) + c(4, 5, 6)?

easy
A. The vectors are concatenated into one longer vector.
B. Only the first elements are added, the rest are ignored.
C. Each element in the first vector is added to the corresponding element in the second vector.
D. An error occurs because vectors cannot be added.

Solution

  1. Step 1: Understand element-wise addition

    In R, adding two vectors of the same length adds each element from the first vector to the matching element in the second vector.
  2. Step 2: Apply addition to given vectors

    Adding c(1, 2, 3) and c(4, 5, 6) results in c(1+4, 2+5, 3+6) which is c(5, 7, 9).
  3. Final Answer:

    Each element in the first vector is added to the corresponding element in the second vector. -> Option C
  4. Quick Check:

    Element-wise addition = Each element in the first vector is added to the corresponding element in the second vector. [OK]
Hint: Add vectors element by element when lengths match [OK]
Common Mistakes:
  • Thinking vectors concatenate instead of adding
  • Assuming only first elements add
  • Expecting an error for vector addition
2.

Which of the following is the correct syntax to subtract two vectors a and b element-wise in R?

easy
A. subtract_vectors(a, b)
B. subtract(a, b)
C. a %minus% b
D. a - b

Solution

  1. Step 1: Recall vector subtraction syntax in R

    In R, element-wise subtraction of vectors uses the minus operator - directly between vectors.
  2. Step 2: Verify given options

    Only a - b is valid R syntax for element-wise subtraction. The other options are not built-in R functions or operators.
  3. Final Answer:

    a - b -> Option D
  4. Quick Check:

    Use - operator for vector subtraction [OK]
Hint: Use '-' operator directly between vectors [OK]
Common Mistakes:
  • Using non-existent functions like subtract()
  • Trying special operators like %minus%
  • Confusing subtraction with other functions
3.

What is the output of the following R code?

v1 <- c(2, 4, 6)
v2 <- c(1, 3, 5)
result <- v1 * v2
print(result)

medium
A. [1] 2 4 6 1 3 5
B. [1] 2 12 30
C. [1] 2 7 11
D. [1] 3 7 11

Solution

  1. Step 1: Understand element-wise multiplication

    In R, multiplying two vectors multiplies each element of the first vector by the corresponding element of the second vector.
  2. Step 2: Calculate each product

    Multiply elements: 2*1=2, 4*3=12, 6*5=30. So the result is c(2, 12, 30).
  3. Final Answer:

    [1] 2 12 30 -> Option B
  4. Quick Check:

    Element-wise multiplication = [1] 2 12 30 [OK]
Hint: Multiply vectors element by element for correct output [OK]
Common Mistakes:
  • Adding instead of multiplying
  • Concatenating vectors instead of multiplying
  • Getting sums instead of products
4.

Consider this R code snippet:

v1 <- c(1, 2, 3)
v2 <- c(4, 5)
result <- v1 + v2
print(result)

What is the issue with this code?

medium
A. Vectors have different lengths causing recycling warning.
B. Syntax error due to missing operator.
C. Result will be NULL because vectors differ in length.
D. No issue; code runs correctly without warnings.

Solution

  1. Step 1: Check vector lengths

    Vector v1 has length 3, v2 has length 2. They differ in length.
  2. Step 2: Understand recycling in R

    R recycles the shorter vector to match the longer one but gives a warning if lengths are not multiples. Here, 3 is not a multiple of 2, so a warning occurs.
  3. Final Answer:

    Vectors have different lengths causing recycling warning. -> Option A
  4. Quick Check:

    Unequal vector lengths cause recycling warning [OK]
Hint: Vectors must be same length or multiples to avoid warnings [OK]
Common Mistakes:
  • Ignoring recycling warnings
  • Expecting syntax errors for length mismatch
  • Assuming result is NULL when lengths differ
5.

You have two vectors representing daily sales for two stores:
store1 <- c(10, 20, 30, 40)
store2 <- c(5, 15, 25, 35)
How do you calculate the total sales per day for both stores combined using vector arithmetic?

hard
A. total_sales <- store1 + store2
B. total_sales <- store1 * store2
C. total_sales <- store1 - store2
D. total_sales <- c(store1, store2)

Solution

  1. Step 1: Understand the goal

    We want total sales per day, so we add sales from both stores for each day.
  2. Step 2: Use element-wise addition

    Adding store1 and store2 element-wise sums daily sales: c(10+5, 20+15, 30+25, 40+35) = c(15, 35, 55, 75).
  3. Final Answer:

    total_sales <- store1 + store2 -> Option A
  4. Quick Check:

    Add vectors element-wise for daily totals [OK]
Hint: Add vectors to combine daily sales totals [OK]
Common Mistakes:
  • Multiplying instead of adding sales
  • Subtracting sales mistakenly
  • Concatenating vectors instead of adding
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard