course content

Course Content

R Introduction: Part I

Operations with VectorsOperations with Vectors

Vectors in R offer a significant advantage due to their flexibility with various operations. For instance, if you have two vectors of the same length, you can easily perform addition or subtraction on an element-by-element basis. Additionally, vectors can undergo arithmetic operations with single numbers, which applies the operation to each element of the vector. For example, let's create a vector with the numbers 10, 20, 30 and add 40, 25, 5 to each corresponding element.

Now, let's go ahead and multiply each element by 2.

R also provides a variety of aggregate and statistical functions. Let's explore two of the most common ones:

  • sum() - calculates and returns the sum of all vector elements.
  • mean() - computes and returns the average value of the vector elements. We will proceed with our previous example and calculate the sum.


Let's revisit our example with a small local store. This time we have data on the number of sales.

ItemPriceItems sold
Dining table1153
Dining chair4515
  1. Construct a vector called sold with the respective values from the Items sold column.
  2. Calculate the revenue by multiplying the prices and sold vectors and then output the result.
  3. Display the total sum of the revenue vector.

Everything was clear?

Section 2. Chapter 11
toggle bottom row