Course Content
R Introduction: Part I
1. Basic Syntax and Operations
R Introduction: Part I
Operations 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.
Task
Let's continue the example with the small local store. Assume this time we have data on the number of sellings.
Item | Price | Items sold |
Sofa | 340 | 5 |
Armchair | 150 | 7 |
Dining table | 115 | 3 |
Dining chair | 45 | 15 |
Bookshelf | 160 | 8 |
- Create a vector named
sold
with the respective values of the Items sold column. - Assign to the
revenue
variable the result of the multiplication ofprices
andsold
. Output the value of this vector. - Output the sum value of
revenue
elements.
Everything was clear?