将具有矩阵作为条目R的元素添加到列表

时间:2019-01-28 20:21:57

标签: r list matrix

当我输出'mat'时,它按预期工作,其中mat提供矩阵的整个列表,mat [1],mat [2]和mat [3]提供第一个第二和第三个元素,即4x4矩阵,所有条目分别等于1、2和3。

但是,当我尝试添加新元素或更改现有元素时,出现错误,并且没有在列表中添加4x4矩阵,而是添加了常规数字。

如何将新矩阵添加到列表中?我也愿意使用list()的替代方法。我对R相对较新,我一直使用x = c(),但这似乎也不适用于矩阵。预先感谢。

输入:

mat = list( matrix (c(1), nrow = 4, ncol = 4, byrow = TRUE),
            matrix (c(2), nrow = 4, ncol = 4, byrow = TRUE),
            matrix (c(3), nrow = 4, ncol = 4, byrow = TRUE) )

mat

mat[2]

mat[1] = matrix(c(0), nrow = 4, ncol = 4, byrow = TRUE)

mat[4] = matrix(c(4), nrow = 4, ncol = 4, byrow = TRUE)

mat

输出:

> mat = list( matrix (c(1), nrow = 4, ncol = 4, byrow = TRUE),
+             matrix (c(2), nrow = 4, ncol = 4, byrow = TRUE),
+             matrix (c(3), nrow = 4, ncol = 4, byrow = TRUE) )
> mat
[[1]]
     [,1] [,2] [,3] [,4]
[1,]    1    1    1    1
[2,]    1    1    1    1
[3,]    1    1    1    1
[4,]    1    1    1    1

[[2]]
     [,1] [,2] [,3] [,4]
[1,]    2    2    2    2
[2,]    2    2    2    2
[3,]    2    2    2    2
[4,]    2    2    2    2

[[3]]
     [,1] [,2] [,3] [,4]
[1,]    3    3    3    3
[2,]    3    3    3    3
[3,]    3    3    3    3
[4,]    3    3    3    3

> mat[2]
[[1]]
     [,1] [,2] [,3] [,4]
[1,]    2    2    2    2
[2,]    2    2    2    2
[3,]    2    2    2    2
[4,]    2    2    2    2

> mat[1] = matrix(c(0), nrow = 4, ncol = 4, byrow = TRUE)
Warning message:
In mat[1] = matrix(c(0), nrow = 4, ncol = 4, byrow = TRUE) :
  number of items to replace is not a multiple of replacement length
> mat[4] = matrix(c(4), nrow = 4, ncol = 4, byrow = TRUE)
Warning message:
In mat[4] = matrix(c(4), nrow = 4, ncol = 4, byrow = TRUE) :
  number of items to replace is not a multiple of replacement length
> mat
[[1]]
[1] 0

[[2]]
     [,1] [,2] [,3] [,4]
[1,]    2    2    2    2
[2,]    2    2    2    2
[3,]    2    2    2    2
[4,]    2    2    2    2

[[3]]
     [,1] [,2] [,3] [,4]
[1,]    3    3    3    3
[2,]    3    3    3    3
[3,]    3    3    3    3
[4,]    3    3    3    3

[[4]]
[1] 4

0 个答案:

没有答案