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!
Diese Übung ist Teil des Kurses
Introduction to R for Finance
Anleitung zur Übung
ret
andweight
for Microsoft and Sony are defined for you again, but this time, in vector form!- Add company names to your
ret
andweight
vectors. - Use vectorized arithmetic to multiply
ret
andweight
together. - Print
ret_X_weight
to see the results. - Use
sum()
to get the totalportf_ret
. - Print
portf_ret
and compare to the last exercise!
Interaktive Übung
Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.
# 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