How to shift each row of a matrix in R

后端 未结 3 665
南旧
南旧 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条回答
  •  萌比男神i
    2021-01-20 02:16

    A head and tail solution doesn't seem as readable as a for loop to me, and may not even be as quick. Nonetheless...

    t( sapply( 0:(nrow(mat)-1) , function(x) c( tail( mat[x+1,] , x ) , head( mat[x+1,] , nrow(mat)-x ) ) ) )
    #     [,1] [,2] [,3]
    #[1,] "a"  "b"  "c" 
    #[2,] "0"  "d"  "e" 
    #[3,] "0"  "0"  "f" 
    

    A for loop version of this could be...

    n <- nrow(mat)
    for( i in 1:n ){
        mat[i,] <- c( tail( mat[i,] , i-1 ) , head( mat[i,] , n-(i-1)  ) )
    }
    

提交回复
热议问题