如何在R中创建矩阵列表 [英] How to create a list of matrix in R

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

问题描述

我想创建2D矩阵列表

> 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

我希望能够将MATS [1]当作x ...

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

推荐答案

尝试

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

在这里您必须像引用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

此方法的一个缺点是,您必须知道列表中必须附加新矩阵的位置,如果您不知道它,或者只是不想使用此方法,那么这里有一个窍门: /p>

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

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

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