Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filling matrices with NA to meet desired dimensions

Tags:

list

r

matrix

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 NAs.

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)
like image 724
John Huang Avatar asked Sep 16 '25 08:09

John Huang


2 Answers

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
like image 150
akrun Avatar answered Sep 18 '25 00:09

akrun


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
like image 30
Darren Tsai Avatar answered Sep 18 '25 00:09

Darren Tsai