Operations with VectorsOperations with Vectors

Vectors in R have one good advantage - flexibility in terms of different operations. For example, if you have two equal length vectors, you can perform an addition/subtraction element-by-element. Also, you can perform all the arithmetic operations with vectors and single numbers - this will operate for each element of a vector. For example, let's create a vector with numbers 10, 20, 30, add numbers 40, 25, 5 to each element, respectively.

Now, we can multiply each element by 2.

R also provides us with different aggregate/statistical functions. Let's consider the most popular two:

  • sum() - will return the sum of all the vector elements.
  • mean() - will return the average value of vector' values. Let's continue the previous example with the sum calculation.


Let's continue the example with the small local store. Assume this time we have data on the number of sellings.

ItemPriceItems sold
Dining table1153
Dining chair4515
  1. Create a vector named sold with the respective values of the Items sold column.
  2. Assign to the revenue variable the result of the multiplication of prices and sold. Output the value of this vector.
  3. Output the sum value of revenue elements.

Everything was clear?

Section 2. Chapter 11
toggle bottom row