[R] Working with Matrix

Neal H. Walfield neal at walfield.org
Fri Jan 4 13:28:00 CET 2013


At Fri, 4 Jan 2013 17:17:40 +0530,
Christofer Bogaso wrote:
> 
> Hello again,
> 
> Let say I have 2 matrices which equal number of columns but different
> number of rows like:
> 
> Mat1 <- matrix(1:20, 4, 5)
> Mat2 <- matrix(1:25, 5, 5)
> 
> Now for each column 1-to-5 I need to fetch the corresponding columns
> of these 2 matrices and add the corresponding elements (ignoring NA
> values if any). Therefore for the 1st column I need to do:
> 
> (1+1), (2+2),...,(4+4), (NA+5)
> 
> and so on
> 
> And the resulting numbers will be stored in some other matrix

This will redimension Mat1 and fill in NAs as you want:

Mat3 = matrix(c(t(Mat1), rep(NA, (nrow(Mat2) - nrow(Mat1)) * ncol(Mat1))),
            byrow=TRUE, ncol=ncol(Mat1))

Then you can do Mat2 + Mat3.

> Also note that, here I gave the example of addition, however, this can
> be any user defined function.

You can use mapply for this:

  mapply(function (a, b) { a + b }, Mat2, Mat3)

Neal




More information about the R-help mailing list