Extracting off-diagonal slice of large matrix

后端 未结 3 1683
野性不改
野性不改 2020-12-09 05:09

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          


        
3条回答
  •  粉色の甜心
    2020-12-09 05:46

    If you want to use upper.tri and lower.tri you could write functions like these:

    cormat <- mapply(rep, 1:6, 6)
    
    u.diags <- function(X, n) {
      X[n:nrow(X),][lower.tri(X[n:nrow(X),])] <- NA
      return(X)
    }
    

    or

    l.diags <- function(X, n) {
      X[,n:ncol(X)][upper.tri(X[,n:ncol(X)])] <- NA
      return(X)
    }
    

    or

    n.diags <- function(X, n.u, n.l) {
      X[n.u:nrow(X),][lower.tri(X[n.u:nrow(X),])] <- NA
      X[,n.l:ncol(X)][upper.tri(X[,n.l:ncol(X)])] <- NA
      return(X)
    }
    

    l.diags(cormat, 3)
    u.diags(cormat, 3)
    n.diags(cormat, 3, 1)
    

提交回复
热议问题