Weighted average (3)
Let's look at an example of recycling. What if you wanted to give equal weight to your Microsoft and Sony stock returns? That is, you want to be invested 50% in Microsoft and 50% in Sony.
ret <- c(7, 9)
weight <- .5
ret_X_weight <- ret * weight
ret_X_weight
[1] 3.5 4.5
ret is a vector of length 2, and weight is a vector of length 1. R reuses the .5 in weight twice to make it the same length of ret, then performs the element-wise arithmetic.
This exercise is part of the course
Introduction to R for Finance
Exercise instructions
- A named vector,
ret, containing the returns of 3 stocks is in your workspace. - Print
retto see the returns of your 3 stocks. - Assign the value of
1/3toweight. This will be the weight that each stock receives. - Create
ret_X_weightby multiplyingretandweight. See how R recyclesweight? sum()theret_X_weightvariable to create your equally weightedportf_ret.- Run the last line of code multiplying a vector of length 3 by a vector of length 2. R reuses the 1st value of the vector of length 2, but notice the warning!
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Print ret
# Assign 1/3 to weight
weight <-
# Create ret_X_weight
ret_X_weight <-
# Calculate your portfolio return
portf_ret <-
# Vector of length 3 * Vector of length 2?
ret * c(.2, .6)