I've got a large nxn matrix and would like to take off-diagonal slices of varying sizes. For example:
1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6 I'd like an R function which, when given the matrix and "width of diagonal slice" would return an nxn matrix of just those values. So for the matrix above and, say, 3, I'd get:
1 x x x x x 1 2 x x x x 1 2 3 x x x x 2 3 4 x x x x 3 4 5 x x x x 4 5 6 At the moment I'm using (forgive me) a for loop which is incredibly slow:
getDiags<-function(ndiags, cormat){ resmat=matrix(ncol=ncol(cormat),nrow=nrow(cormat)) dimnames(resmat)<-dimnames(cormat) for(j in 1:ndiags){ resmat[row(resmat) == col(resmat) + j] <- cormat[row(cormat) == col(cormat) + j] } return(resmat) } I realise that this is a very "un-R" way to go about solving this problem. Is there a better way to do it, probably using diag or lower.tri?