Get startedGet started for free

Weighted average (2)

Wait a minute, Lore taught us a much better way to do this! Remember, R does arithmetic with vectors! Can you take advantage of this fact to calculate the portfolio return more efficiently? Think carefully about the following code:

ret <- c(5, 7)
weight <- c(.4, .6)

ret_X_weight <- ret * weight

sum(ret_X_weight)

[1] 6.2

First, calculate ret * weight, which multiplies each element in the vectors together to create a new vector ret_X_weight. All you need to do then is add up the pieces, so you use sum() to sum up each element in the vector.

Now its your turn!

This exercise is part of the course

Introduction to R for Finance

View Course

Exercise instructions

  • ret and weight for Microsoft and Sony are defined for you again, but this time, in vector form!
  • Add company names to your ret and weight vectors.
  • Use vectorized arithmetic to multiply ret and weight together.
  • Print ret_X_weight to see the results.
  • Use sum() to get the total portf_ret.
  • Print portf_ret and compare to the last exercise!

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Weights, returns, and company names
ret <- c(7, 9)
weight <- c(.2, .8)
companies <- c("Microsoft", "Sony")

# Assign company names to your vectors
names(ret) <- 
names(weight) <- 

# Multiply the returns and weights together 
ret_X_weight <- 

# Print ret_X_weight


# Sum to get the total portfolio return
portf_ret <-

# Print portf_ret
Edit and Run Code