Vectors and Matrices

Vector manipulation

calculations are vectorized

dan <- 100
rob <- 50
total <- dan + rob
dan <- c(100, 200, 150)
rob <- c(50, 75, 100)
monthly_total <- dan + rob
monthly_total
Sum(monthly_total)

a <- c(2.2, 12, 7)
b <- c(11.5, 8, 3.4)

c <- a-b
c
d <- a * b
d
e <- 2
f <- a* e
f

<aside> 📖 4.4 24.0 14.0

</aside>

Assume you have 40% of your cash in Apple stock, and 60% of your cash in IBM stock. If, in January, Apple earned 5% and IBM earned 7%, what was your total portfolio return?

To calculate this, take the return of each stock in your portfolio, and multiply it by the weight of that stock. Then sum up all of the results. For this example, you would do:

6.2 = 5 * .4 + 7 * .6

Or, in variable terms:

portf_ret <- apple_ret * apple_weight + ibm_ret * ibm_weight

# Weights and returns
micr_ret <- 7
sony_ret <- 9
micr_weight <- .2
sony_weight <- .8

# Portfolio return
portf_ret <- micr_ret*micr_weight + sony_ret * sony_weight

portf_ret
[1] 8.6

Weighted average(2)

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

# 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) <- companies
names(weight) <- companies

# Multiply the returns and weights together 
ret_X_weight <- ret*weight

# Print ret_X_weight
print(ret_X_weight)

# Sum to get the total portfolio return
portf_ret <- sum(ret_X_weight)

# Print portf_ret
print(portf_ret)