user3231352
user3231352

Reputation: 809

avoiding loops and multiply lists with matrices elements

I'm working with some lists and matrices, and I'm having some problems to handle the data properly. Let's say I define the following matrices and lists (just as an example):

m1 <-array(rexp(5),dim=c(3,3,3))
mn <-apply(m1,1:2,mean)   
ms <-apply(m1,1:2,sum)
msqr <-apply(ms,1:2,sqrt)
list1 <- list(mn,ms)
list2 <- list(ms,msqr)

Then, I would like to substract mn from m1(which have different dimensions), but avoiding loops..I mean, so far, I was doing something like:

dif <- array(NA,dim=c(3,3,3))
      for(i in 1:3){
        for(j in 1:3){
         dif[i,j,]<- m1[i,j,]-mn[i,j]
         }
        }

On the other hand , I want to multiply both lists: list1 and list2 (element by element), to get another one, list3 with the same number of elements. I was trying with sapply..but I am not doing well ..I guess I could use for both examples some functions (mapply or sapply) , but I can not see how..any suggestion?

Thanks!

Upvotes: 1

Views: 42

Answers (1)

akrun
akrun

Reputation: 886998

For the first part, we can replicate the 'mn' values to create an array of the same size as 'm1' and then do the elementwise subtraction

dif1 <- m1-array(rep(mn, dim(m1)[3]), dim(m1))
identical(dif, dif1)
#[1] TRUE

and for the second case, mapply can be used to do multiplication between the corresponding elements of both lists.

mapply(`*`, list1, list2, SIMPLIFY = FALSE)

Or we unlist the lists , do the * and then relist it

relist(unlist(list1) * unlist(list2), skeleton = list1)

Upvotes: 2

Related Questions