簡體   English   中英

如何在R中移動矩陣的每一行

[英]How to shift each row of a matrix in R

我有這種形式的矩陣:

a b c
d e 0
f 0 0

我想將它轉換成這樣的東西:

a b c
0 d e
0 0 f

轉變模式是這樣的:

shift by 0 for row 1
shift by 1 for row 2
shift by 2 for row 3
...
shift by n-1 for row n

當然,這可以通過for循環來完成。 我想知道是否有更好的方法?

假設您的示例具有代表性,即您始終使用字母和零的三角形結構:

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" 

headtail解決方案對我來說似乎不像for循環那樣可讀,甚至可能不那么快。 不過...

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" 

這個for循環版本可能是......

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

我認為這就是你所需要的:

 mat<-matrix(1:25,5)
 mat
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    6   11   16   21
[2,]    2    7   12   17   22
[3,]    3    8   13   18   23
[4,]    4    9   14   19   24
[5,]    5   10   15   20   25
 for(j in 2:nrow(mat) ) mat[j,]<-mat[j, c(j:ncol(mat),1:(j-1))]
 mat
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    6   11   16   21
[2,]    7   12   17   22    2
[3,]   13   18   23    3    8
[4,]   19   24    4    9   14
[5,]   25    5   10   15   20

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM