R:如何将矩阵每行中的条目加倍并插入新行
mylist <- list(matrix(c(1, 3, -1, 0, 2, 1), nrow = 2, byrow = TRUE),
matrix(c(-2, 0, 10, 1, 2, 9, 2, 0, 0), nrow = 3, byrow = TRUE))
> mylist
[[1]]
[,1] [,2] [,3]
[1,] 1 3 -1
[2,] 0 2 1
[[2]]
[,1] [,2] [,3]
[1,] -2 0 10
[2,] 1 2 9
[3,] 2 0 0
我有一个称为myList
的矩阵列表,其中矩阵的尺寸可能有所不同。对于每个矩阵,我想将行值加倍并将其插入下面的新行。我所需的输出如下:
[[1]]
[,1] [,2] [,3]
[1,] 1 3 -1
[2,] 2 6 -2
[3,] 0 2 1
[4,] 0 4 2
[[2]]
[,1] [,2] [,3]
[1,] -2 0 10
[2,] -4 0 20
[3,] 1 2 9
[4,] 2 4 18
[5,] 2 0 0
[6,] 4 0 0
mylist <- list(matrix(c(1, 3, -1, 0, 2, 1), nrow = 2, byrow = TRUE),
matrix(c(-2, 0, 10, 1, 2, 9, 2, 0, 0), nrow = 3, byrow = TRUE))
> mylist
[[1]]
[,1] [,2] [,3]
[1,] 1 3 -1
[2,] 0 2 1
[[2]]
[,1] [,2] [,3]
[1,] -2 0 10
[2,] 1 2 9
[3,] 2 0 0
I have a list of matrices called mylist
where the dimensions of the matrices can differ. For each matrix, I want to double the row values and insert it as a new row underneath. My desired output is as follows:
[[1]]
[,1] [,2] [,3]
[1,] 1 3 -1
[2,] 2 6 -2
[3,] 0 2 1
[4,] 0 4 2
[[2]]
[,1] [,2] [,3]
[1,] -2 0 10
[2,] -4 0 20
[3,] 1 2 9
[4,] 2 4 18
[5,] 2 0 0
[6,] 4 0 0
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在
lapply
中,rep
吃掉使用seq_len
和nrow
找到的每一行索引,并重复乘以1: 2 利用回收利用。
In an
lapply
rep
eat each row index found usingseq_len
withnrow
and multiply repeatedly by1:2
exploiting recycling.您可以使用
rbind
,但是您需要输入行才能在下面乘以乘以:You can use
rbind
but you need to permute rows to get multiplied row beneath:另一个基本R方法也使用
rbind
do.call 。Another base R approach which also utilises the
rbind
function withdo.call
.