Skip to content

Working with Matrix

8 messages · Jorge I Velez, Neal H. Walfield, Rui Barradas +3 more

#
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

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

Is there any R way to do that, without using any for-loop?

Thanks and regards,
#
At Fri, 4 Jan 2013 17:17:40 +0530,
Christofer Bogaso wrote:
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.
You can use mapply for this:

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

Neal
#
Hello,

Using part of your code, it's possible to do without Reduce, have foo 
(fun, below) do the job.

fun <- function(x, y, FUN = `+`){
     if(nrow(x) < nrow(y)){
         nas <- matrix(NA, ncol = ncol(x), nrow = nrow(y) - nrow(x))
         x <- rbind(x, nas)
     }else{
         nas <- matrix(NA, ncol = ncol(y), nrow = nrow(x) - nrow(y))
         y <- rbind(y, nas)
     }
     FUN(x, y)
}

fun(Mat1, Mat2)
fun(Mat1, Mat2, `*`)  # Note the back quotes


Hope this helps,

Rui Barradas
Em 04-01-2013 12:06, Jorge I Velez escreveu:
#
Hello Rui/Jorge,

This is shorter, and probably needs less memory for large matrices as
you create
an other copy by defining nas:

matrixOp <- function(m1, m2, op=`+`) {
 rows <- min(nrow(m1), nrow(m2))
 cols <- ncol(m1)
 op(m1[1:rows, 1:cols], m2[1:rows, 1:cols])
}

Best,

mem
On 4 January 2013 14:08, Rui Barradas <ruipbarradas at sapo.pt> wrote:
#
Thanks all for your help. However I was looking for following type of operation:

Mat1 <- Mat2 <- matrix(1:20, 4, 5); Mat2[1,5] <- 200
Mat = rbind(Mat1, Mat2)
apply(Mat, 2, function(x) return(all(x[1:4] == x[5:8])))

However I believe there must be some smarter method using
***mapply()*** or something like that. To me above operation looks
very trivial! Also underlying function may be more complected

Is it real trivial or some better method is available?

Thanks and regards,
On Fri, Jan 4, 2013 at 9:24 PM, Suzen, Mehmet <msuzen at gmail.com> wrote:
#
On Jan 4, 2013, at 10:46 AM, Christofer Bogaso wrote:

            
Perhaps:
[1]  TRUE  TRUE  TRUE  TRUE FALSE