如何在R中移动矩阵的每一行 [英] How to shift each row of a matrix in R

查看:143
本文介绍了如何在R中移动矩阵的每一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种形式的矩阵:

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

移位模式是这样:

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循环来完成。我想知道
是否有更好的方法吗?

This can be done with a for loop of course. I am wondering if there is a better way?

推荐答案

假设您的示例具有代表性,即您有始终是字母和零的三角形结构:

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" 

这篇关于如何在R中移动矩阵的每一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆