I think there are better solutions but mine will handle a 1x1 matrix as well, which is really just a vector.
You can use the function I've made here resize_matrix in your code however you'd like. It is pretty verbose, but I thinks it's easy to understand exactly what it's doing under the hood. Note: the function is meant to be used in an lapply() call.
The input:
m1 <- matrix(1:9, 3,3)
m2 <- matrix(1:4, 2,2)
m3 <- matrix(1:3, 3, 1)
m4 <- matrix(1:3, 1, 3)
m5 <- matrix(1, 1, 1)
# Matrices into a list
l1 <- list(m1, m2, m3, m4, m5)
l1
#> [[1]]
#> [,1] [,2] [,3]
#> [1,] 1 4 7
#> [2,] 2 5 8
#> [3,] 3 6 9
#>
#> [[2]]
#> [,1] [,2]
#> [1,] 1 3
#> [2,] 2 4
#>
#> [[3]]
#> [,1]
#> [1,] 1
#> [2,] 2
#> [3,] 3
#>
#> [[4]]
#> [,1] [,2] [,3]
#> [1,] 1 2 3
#>
#> [[5]]
#> [,1]
#> [1,] 1
The function:
resize_matrix <- function(mat, desired_rows = 3, desired_columns = 3){
needed_cols <- desired_columns - dim(mat)[2]; needed_cols
needed_rows <- desired_rows - dim(mat)[1]; needed_rows
if (dim(mat)[1] == 1 & dim(mat)[2] == 1){
# we're give a matrix with a single value, expand correctly
final_mat <- matrix(NA, nrow = desired_rows, ncol = desired_columns)
final_mat[1,1] <- mat
} else if (needed_cols > 0 & needed_rows > 0){
# we need to add both rows and columns
col_res <- rep(NA, needed_rows)
row_res <- rep(NA, needed_cols)
mat_temp1 <- rbind(mat, col_res)
final_mat <- unname(cbind(mat_temp1, row_res))
} else if (needed_cols > 0 & needed_rows == 0) {
# we need to add only columns
row_res <- matrix(rep(NA, needed_cols),
ncol = needed_cols, nrow = desired_rows)
final_mat <- unname(cbind(mat, row_res))
} else if (needed_cols == 0 & needed_rows > 0) {
# we need to add only rows
col_res <- matrix(rep(NA, needed_rows),
ncol = desired_columns, nrow = needed_rows)
final_mat <- unname(rbind(mat, col_res))
} else {
# we don't need to add anything, return the matrix
final_mat <- mat
}
return(final_mat)
}
The output:
lapply(l1, FUN = resize_matrix)
#> [[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
#>
#> [[4]]
#> [,1] [,2] [,3]
#> [1,] 1 2 3
#> [2,] NA NA NA
#> [3,] NA NA NA
#>
#> [[5]]
#> [,1] [,2] [,3]
#> [1,] 1 NA NA
#> [2,] NA NA NA
#> [3,] NA NA NA
Created on 2022-04-16 by the reprex package (v2.0.1)