Exercise

# 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!

Instructions

**100 XP**

`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!