jameselmore
jameselmore

Reputation: 442

Merging Two Matrices

I've done a little bit of digging for this result but most of the questions on here have information in regards to the cbind function, and basic matrix concatenation. What I'm looking to do is a little more complicated.

Let's say, for example, I have an NxM matrix whose first column is a unique identifier for each of the rows (and luckily in this instance is sorted by that identifier). For reasons which are inconsequential to this inquiry, I'm splitting the rows of this matrix into (n_i)xM matrices such that the sum of n_i = N.

I'm intending to run separate analysis on each of these sub-matrices and then combine the data together again with the usage of the unique identifier.

An example: Let's say I have matrix data which is 10xM. After my split, I'll receive matrices subdata1 and subdata2. If you were to look at the contents of the matrices:

data[,1] = 1:10
subdata1[,1] = c(1,3,4,6,7)
subdata2[,1] = c(2,5,8,9,10)

I then manipulate the columns of subdata1 and subdata2, but preserve the information in the first column. I would like to combine this matrices again such that finaldata[,1] = 1:10, where finaldata is a result of the combination.

I realize now that I could use rbind and the sort the matrix, but for large matrices that is very inefficient.

I know R has some great functions out there for data management, is there a work around for this problem?

Upvotes: 0

Views: 607

Answers (2)

Neal Fultz
Neal Fultz

Reputation: 9696

If you know they are matrices, you can do this with multidimensional arrays:

X <- matrix(1:100, 10,10)
s1 <- X[seq(1, 9,2), ]
s2 <- X[seq(2,10,2), ]
XX <- array(NA, dim=c(2,5,10) )
XX[1, ,] <- s1 #Note two commas, as it's a 3D array
XX[2, ,] <- s2
dim(XX) <- c(10,10)
XX

This will copy each element of s1 and s2 into the appropriate slice of the array, then drop the extra dimension. There's a decent chance that rbind is actually faster, but this way you won't need to re-sort it.

Caveat: you need equal sized splits for this approach.

Upvotes: 0

user1477388
user1477388

Reputation: 21440

I may not fully understand your question, but as an example of general use, I would typically convert the matrices to dataframes and then do something like this:

combi <- rbind(dataframe1, dataframe2)

Upvotes: 0

Related Questions