0

When I output 'mat', it works as expected, with mat giving the whole list of matrices and mat[1], mat[2] and mat[3] giving the first second and third elements, namely 4x4 matrices with all entries equal to 1, 2 and 3 respectively.

However when I try to add a new element or change an existing one, I get an error, and instead of adding a 4x4 matrix to the list, it just adds a regular number.

How would I add a new matrix to the list? I am also open to using alternatives to list(). I am relatively new to R and I'd always used x = c(), but that doesn't seem to work for matrices either. Thanks in advance.

Input:

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

Output:

> 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
  • Use `[[` not `[` when referencing a single list item. [See this R-FAQ for some background](https://stackoverflow.com/q/1169456/903061). – Gregor Thomas Jan 28 '19 at 20:25
  • `mat[[4]] = matrix(1:4, 2)` will work, and for your earlier assignments use `mat[[1]] = matrix(...)` instead of `mat[1] = matrix(...)`. – Gregor Thomas Jan 28 '19 at 20:29

0 Answers0