问题
I believe that a similar question was asked here, but I can't seem to find it anymore.
I have two matrices with different dimensions, and I want to equalise them so that I can combine them in an array.
for example, I have the following two matrices:
a <- matrix(1:6, 3, 2)
b <- matrix(1:12, 4, 3)
a
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
b
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 2 6 10
[3,] 3 7 11
[4,] 4 8 12
Because I am working with time series data, I would like the added rows/colums to have NAs in them. In my example, matrix a would get an extra column and an extra row only containing NAs like this:
[,1] [,2] [,3]
[1,] 1 4 NA
[2,] 2 5 NA
[3,] 3 6 NA
[4,] NA NA NA
In my dataset I will have 79 matrices with unequal dimensions, and I need to make them as big as the matrix with the largest dimensions.
回答1:
If b
is the largest matrix, you can create a matrix with the same dimensions as b
, filled with NA
, and replace the rows and columns corresponding to the smaller matrix a
with the values of a
:
a2 <- "[<-"(x = matrix(NA, nrow = nrow(b), ncol = ncol(b)),
i = 1:nrow(a), j = 1:ncol(a),
value = a)
a2
# [,1] [,2] [,3]
# [1,] 1 4 NA
# [2,] 2 5 NA
# [3,] 3 6 NA
# [4,] NA NA NA
Example with several matrices, where we find the largest matrix and pad all matrices with NA
to match the dimension of the largest.
# create some matrices of different size
a <- matrix(1:6, nrow = 3, ncol = 2)
b <- matrix(1:12, nrow = 4, ncol = 3)
c <- matrix(1:4, nrow = 2, ncol = 2)
# put them in a list
l <- list(a, b, c)
# index of largest (here, max number of rows) matrix in the list
id <- which.max(unlist((lapply(l, nrow))))
# pad matrices with NA
l2 <- lapply(l, function(x){
x <- "[<-"(x = matrix(NA, nrow = nrow(l[[id]]), ncol = ncol(l[[id]])),
i = 1:nrow(x), j = 1:ncol(x),
value = x)
})
l2
# [[1]]
# [,1] [,2] [,3]
# [1,] 1 4 NA
# [2,] 2 5 NA
# [3,] 3 6 NA
# [4,] NA NA NA
#
# [[2]]
# [,1] [,2] [,3]
# [1,] 1 5 9
# [2,] 2 6 10
# [3,] 3 7 11
# [4,] 4 8 12
#
# [[3]]
# [,1] [,2] [,3]
# [1,] 1 3 NA
# [2,] 2 4 NA
# [3,] NA NA NA
# [4,] NA NA NA
回答2:
As you only want to extend the small matrix with NA
, we can use a simple approach such as:
create a matrix as big as
b
, with onlyNA
. Code:extended.a = matrix(NA,nrow(b),ncol(b))
fill this matrix with the values from
a
. Code:extended.a[cbind(rep(1:nrow(a),ncol(a)), rep(1:ncol(a),each=nrow(a)))] = a
edit:
As per Roland's suggestion, you can also get the vector of indices with which(..., arr.ind=TRUE)
.
For example, which(TRUE | a, arr.ind=TRUE)
Or even: which(matrix(TRUE,nrow(a),ncol(a), arr.ind=TRUE)
Or far better, using the expand.grid
function: expand.grid(1:nrow(a), 1:ncol(a))
来源:https://stackoverflow.com/questions/22513862/equalizing-matrices-for-combining-in-abind-r