Hello I have created a list with the following loop
portfolio_covlist2<-list()
for (i in 1:25) {
a<-covst[Stock.mix.2[i,],Stock.mix.2[i,]]
a<-list(matrix(a,nrow=2))
portfolio_covlist2[i] <- a
}
The data then look like this
[[1]]
[,1] [,2]
[1,] 0.009168161 0.001283940
[2,] 0.001283940 0.002723437
[[2]]
[,1] [,2]
[1,] 0.021906044 0.002600486
[2,] 0.002600486 0.009508103
I want to then be able to multiply these like
w2*portfolio_covlist2[1]*t(w2)
to give me a standard deviation of the mixes. but I get this error:
Error in w2 * portfolio_covlist2[1] :
non-numeric argument to binary operator
the w vectors confirm as numeric but the list types do not...HELP!
thanks
You are inadvertently trying to multiply a list instead of a matrix.
And incidentally, I think you want %*%
for matrix multiplication instead of *
which will do element-wise multiplication.
L <- list(structure(c(0.009168161, 0.00128394, 0.00128394, 0.002723437), .Dim = c(2L, 2L)), structure(c(0.021906044, 0.002600486, 0.002600486, 0.009508103), .Dim = c(2L, 2L)))
m <- matrix(1:4, nr=2)
m %*% L[1] %*% t(m)
# Error in m %*% L[1] : requires numeric/complex matrix/vector arguments
1
m %*% L[[1]] %*% t(m)
# [,1] [,2]
# [1,] 0.04138273 0.06385697
# [2,] 0.06385697 0.10079068
The reason is that with list
, the [
operator returns a list with the selected elements within it, while [[
returns a single (not-listed) element:
L[1]
# [[1]] <--- this means it is still in a list, even just length 1
# [,1] [,2]
# [1,] 0.009168161 0.001283940
# [2,] 0.001283940 0.002723437
L[[1]]
# [,1] [,2]
# [1,] 0.009168161 0.001283940
# [2,] 0.001283940 0.002723437