I have a list of matrices that I've created. The matrices in the list have different dimensions, and I would like to fill the matrices that don't have a 3x3 dimension with NA
s.
I have included my expected outcome below. I would like to include this in a if
statement, where if the matrix in the list doesn't have a 3x3 dimension I would like to added empty columns/rows to those matrices and fill them with an NA
. Is there an efficient way of doing this in base r?
# Created Matrices
m1 <- matrix(1:9, 3,3)
m2 <- matrix(1:4, 2,2)
m3 <- matrix(1:3, 3, 1)
# Matrices into a list
l1 <- list(m1, m2, m3)
l1
# Expected Matrices and outputs
m2_new <- matrix(c(1,2,NA,3, 4, rep(NA, 4)), 3,3)
m3_new <- matrix(c(1,2,3,rep(NA, 6)), 3,3)
expected <- list(m1, m2_new, m3_new)
One option would be to create a NA
matrix
and replace
the values with the 'x' based on the row/col
index
dummy <- matrix(ncol = 3, nrow = 3)
l2 <- lapply(l1, function(x) replace(dummy, cbind(c(row(x)), c(col(x))), x))
-checking
> all.equal(l2, expected)
[1] TRUE
You can replace parts of a matrix with matrix indexing.
mat <- array(dim = c(3, 3))
lapply(l1, function(x) `[<-`(mat, 1:nrow(x), 1:ncol(x), x))
# [[1]]
# [,1] [,2] [,3]
# [1,] 1 4 7
# [2,] 2 5 8
# [3,] 3 6 9
#
# [[2]]
# [,1] [,2] [,3]
# [1,] 1 3 NA
# [2,] 2 4 NA
# [3,] NA NA NA
#
# [[3]]
# [,1] [,2] [,3]
# [1,] 1 NA NA
# [2,] 2 NA NA
# [3,] 3 NA NA
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With