Operations with Vectors
Vectors in R support arithmetic operations. Operations can be performed element by element between two vectors of the same length, or between a vector and a single number (applied to each element).
Element-wise Operations
Vectors of equal length can be combined with arithmetic operators, computing results element by element.
Example
123456a <- c(10, 20, 30) b <- c(40, 25, 5) # Addition (element by element) c <- a + b c
Scalar Operations
A single number can be combined with a vector, and the operation is applied to every element.
Example
1234567a <- c(10, 20, 30) b <- c(40, 25, 5) c <- a + b # Multiply each element by 2 d <- c * 2 d
Aggregate Functions
R also has many functions, such as sum()
and mean()
, that work directly on vectors.
Example
123456789a <- c(10, 20, 30) b <- c(40, 25, 5) c <- a + b d <- c * 2 # Calculate the sum sum(d) # Calculate the average mean(d)
Swipe to start coding
You work at a store. During the day, you were able to sell the following items:
Item | Price | Items sold |
---|---|---|
Sofa | $340 | 5 |
Armchair | $150 | 7 |
Dining table | $115 | 3 |
Dining chair | $45 | 15 |
Bookshelf | $160 | 8 |
Your task is to:
- Construct a vector called
sold
with the respective values from the Items sold column. - Calculate the
revenue
by multiplying theprices
andsold
vectors. - Display the total sum of the
revenue
vector.
Solution
Thanks for your feedback!
single
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Awesome!
Completion rate improved to 2.27
Operations with Vectors
Swipe to show menu
Vectors in R support arithmetic operations. Operations can be performed element by element between two vectors of the same length, or between a vector and a single number (applied to each element).
Element-wise Operations
Vectors of equal length can be combined with arithmetic operators, computing results element by element.
Example
123456a <- c(10, 20, 30) b <- c(40, 25, 5) # Addition (element by element) c <- a + b c
Scalar Operations
A single number can be combined with a vector, and the operation is applied to every element.
Example
1234567a <- c(10, 20, 30) b <- c(40, 25, 5) c <- a + b # Multiply each element by 2 d <- c * 2 d
Aggregate Functions
R also has many functions, such as sum()
and mean()
, that work directly on vectors.
Example
123456789a <- c(10, 20, 30) b <- c(40, 25, 5) c <- a + b d <- c * 2 # Calculate the sum sum(d) # Calculate the average mean(d)
Swipe to start coding
You work at a store. During the day, you were able to sell the following items:
Item | Price | Items sold |
---|---|---|
Sofa | $340 | 5 |
Armchair | $150 | 7 |
Dining table | $115 | 3 |
Dining chair | $45 | 15 |
Bookshelf | $160 | 8 |
Your task is to:
- Construct a vector called
sold
with the respective values from the Items sold column. - Calculate the
revenue
by multiplying theprices
andsold
vectors. - Display the total sum of the
revenue
vector.
Solution
Thanks for your feedback!
single