Search code examples
rtibble

How to multiply each row in a tibble with a matrix to get standard deviation?


I have one tibble and one matrix. The tibble contains a large dataset of random weights between 0 and 1. Here just a small fraction of the original dataset (original dataset has 15.000 rows) with random numbers:

library(tidyquant)
library(tidyverse)

weights_ptf <- tibble(a = runif(10, min=0, max=1), b = runif(10, min=0, max=1), 
             c = runif(10, min=0, max=1), d = runif(10, min=0, max=1), e = runif(10, min=0, max=1))

The matrix is a covariance matrix. For the sake of simplification the matrix looks in this case like:

CovMat <- matrix( 
  c(runif(5, min=0.0001, max=0.0002), runif(5, min=0.0001, max=0.0002), runif(5, min=0.0001, max=0.0002), 
    runif(5, min=0.0001, max=0.0002), runif(5, min=0.0001, max=0.0002), runif(5, min=0.0001, max=0.0002)), 
    nrow=5, 
    ncol=5) 

colnames(CovMat) <- (c("a", "b", "c", "d", "e"))
rownames(CovMat) <- (c("a", "b", "c", "d", "e"))

I would like to calculate for each single row in weights_ptf the standard deviation according to the formula: sqrt(t(wts) %*% (CovMat %*% wts)). wts in this case would be each single row in weights_ptf.

I hope my problem is clear. Any help would be much appreciated.

Thanks in advance!


Solution

  • for set.seed(2L) used for creating data

    apply(weights_ptf, 1, function(x) sqrt(t(x) %*% (CovMat %*% x)))
    # [1] 0.02935053 0.02150601 0.03854272 0.01795160 0.03706881 0.04465907 0.03659552 0.02438940 0.03720857 0.01956361