Search code examples
rcorrelationdiagonal

Set diagonals of a large array to zero in R


I have a dynamic correlation network as a result of DCC-GARCH. I need to convert diagonals to zero for each array. It is daily data so I have correlation arrays each day. when I type

print(Corr)

The array looks like this for a day (I can only show a page as only one day fits into the page but I have correlation array for 1000 days) enter image description here

How can I convert diagonals to zero at once?


Solution

  • Try this:

    Corr <- array( apply( Corr, 3, function(x) { 
              x[ row(x) == col(x) ] <-0; x} ), dim(Corr) )
    

    The apply function can work with any of the dimensions, and this will deliver a matrix-"slice" to the inner anonymous function and set its diagonal to zero.