Search code examples
rdiagonal

Main diagonal into anti-diagonal


I need to transform main diagonal

{matrix(
1 1 1 1,
0 2 2 2,
0 0 3 3,
0 0 0 4)
}

into:

{matrix(
0 0 0 1,
0 0 1 2,
0 1 2 3,
1 2 3 4)
}

I tried all operators I could find t(), arev(), flipud(), apply(x,2,rev) and so on. Without a positive result. Hope you can help me.


Solution

  • Does this work for you? Takes each column and 'rotates' (for lack of a better word) x places, where x is the column index.

    res <- sapply(1:ncol(input),function(x){
      #get relevant column
      base <- input[,x]
      n <- length(base)
      indices <- 1:n
      #reshuffle indices: first above x, then below x
      out <- base[c(indices[indices>x],indices[indices<=x])]
      out
    })
    
    all(res==output)
    [1] TRUE
    

    data used:

    input <- structure(c(1, 0, 0, 0, 1, 2, 0, 0, 1, 2, 3, 0, 1, 2, 3, 4), .Dim = c(4L, 
    4L))
    output <- structure(c(0, 0, 0, 1, 0, 0, 1, 2, 0, 1, 2, 3, 1, 2, 3, 4), .Dim = c(4L, 
    4L))