list 如何在R中创建矩阵列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13765144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:55:46  来源:igfitidea点击:

How to create a list of matrix in R

rlistmatrix

提问by ManInMoon

I want to create a list of 2D matrices

我想创建一个二维矩阵列表

> x
     [,1] [,2]
[1,]    1    6
[2,]    2    7
[3,]    3    8
[4,]    4    9
[5,]    5   10

> y
     [,1] [,2]
[1,]  301  306
[2,]  302  307
[3,]  303  308
[4,]  304  309
[5,]  305  310

> MATS<-c(x,y)

> MATS[1]
[1] 1

I would like to be able to refer to MATS[1] as if it where x...

我希望能够引用 MATS[1] 就好像它在 x...

采纳答案by Jilber Urbina

Try

尝试

x <- matrix(1:10, ncol=2)
y <- x+300

MATS <- list(x, y) # use 'list' instead of 'c' to create a list of matrices
MATS
[[1]]
     [,1] [,2]
[1,]    1    6
[2,]    2    7
[3,]    3    8
[4,]    4    9
[5,]    5   10

[[2]]
     [,1] [,2]
[1,]  301  306
[2,]  302  307
[3,]  303  308
[4,]  304  309
[5,]  305  310

Here you have to refer to MATS[[1]]as if it were x

在这里你必须参考,MATS[[1]]好像它是x

If you want to append a new matrix to the exiting list try

如果要将新矩阵附加到现有列表中,请尝试

z <- x+500
MATS[[3]] <- z  # appeding a new matrix to the existing list
MATS

[[1]]
     [,1] [,2]
[1,]    1    6
[2,]    2    7
[3,]    3    8
[4,]    4    9
[5,]    5   10

[[2]]
     [,1] [,2]
[1,]  301  306
[2,]  302  307
[3,]  303  308
[4,]  304  309
[5,]  305  310

[[3]]
     [,1] [,2]
[1,]  501  506
[2,]  502  507
[3,]  503  508
[4,]  504  509
[5,]  505  510

One drawback of this approach is that you have to know the position in the list where you have to append the new matrix, if you don't know it or simply if you dont want this approach, then here's a trick:

这种方法的一个缺点是您必须知道列表中必须附加新矩阵的位置,如果您不知道或者只是不想使用这种方法,那么这里有一个技巧:

unlist(list(MATS, list(z)), recursive=FALSE) # will give u the same list :D