Nested For loop in R -
this simple question taking time new in r.
i'm trying write code variance of portfolio.
for example, have following :-
weight=c(0.3,0.2,0.5) cov = matrix( c(0.2, 0.4, 0.3, 0.4, 0.5, 0.3,0.3,0.3,0.4),nrow=3, ncol=3, byrow = true) (i in 1:3){ (j in 1:3) { port = sum((weight[i]^2) * (cov[i,i]^2)) + sum(weight[i] *weight[j]* cov[i,j]) }} the answer if calculate manually should 0.336. r gave me port=0.12 wrong. mistake?
first calculate matrix product w %*% t(w):
tcrossprod(weight) # [,1] [,2] [,3] #[1,] 0.09 0.06 0.15 #[2,] 0.06 0.04 0.10 #[3,] 0.15 0.10 0.25 then multiply variance-covariance matrix , take sum of elements:
sum(tcrossprod(weight) * cov) #[1] 0.336 or loop (inefficient):
port <- 0 (i in 1:3){ (j in 1:3) { port <- if (i == j) { port + sum((weight[i]^2) * (cov[i,i])) } else { port + sum(weight[i] *weight[j]* cov[i,j]) } } } port #[1] 0.336 note variance-covariance matrix typically contains variances (sigma_i^2) on diagonal.

Comments
Post a Comment