How to shift each row of a matrix in R

后端 未结 3 631
南旧
南旧 2021-01-20 01:36

I have a matrix of this form:

a b c
d e 0
f 0 0

and I want to transform it into something like this:

a b c
0 d e
0 0 f
         


        
3条回答
  •  走了就别回头了
    2021-01-20 02:03

    Assuming that your example is representative, i.e., you have always a triangle structure of letters and zeros:

    mat <- structure(c("a", "d", "f", "b", "e", "0", "c", "0", "0"), 
                     .Dim = c(3L, 3L), .Dimnames = list(NULL, NULL))
    res <- matrix(0, nrow(mat), ncol(mat))
    res[lower.tri(res, diag=TRUE)] <- t(mat)[t(mat)!="0"]
    t(res)
    #     [,1] [,2] [,3]
    # [1,] "a"  "b"  "c" 
    # [2,] "0"  "d"  "e" 
    # [3,] "0"  "0"  "f" 
    

提交回复
热议问题