Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: function on all column combinations from two data frames using nested apply

Given two matrices with the same number of columns.

m1 <- matrix(1:12, ncol=3)
m2 <- matrix(10:2, ncol=3)

Say I have a function that takes two vectors and do something like the product of each vectors min (toy example):

fun <- function(v1, v2)(min(v1)*min(v2))

I can't get my head around how to do the function on all combinations of columns by using two nested apply calls. To use apply on m1 versus first column is like:

apply(m1, 2, fun, m2[,1])

Im stuck with looping through all m2's columns like:

m3<-matrix(NA, ncol=3, nrow=3)
for(c in 1:ncol(m2)){ 
m3[,c] <- apply(m1, 2, fun, m2[,c])
}

This gives

> m3
     [,1] [,2] [,3]
[1,]   10    9    8
[2,]   50   45   40
[3,]   90   81   72

So how to frame this loop as an apply ?

EDIT: the code had an error - sorry. See edit

like image 713
user3375672 Avatar asked Sep 03 '25 15:09

user3375672


1 Answers

If you are interested using nested apply, we can try

apply(m1, 2, function(x) apply(m2, 2, function(y) min(x) * min(y)))

#     [,1] [,2] [,3]
#[1,]    8   40   72
#[2,]    5   25   45
#[3,]    2   10   18

As you already have the function defined,

apply(m1, 2, function(x) apply(m2, 2, fun, x))

would be simpler.

like image 59
Ronak Shah Avatar answered Sep 05 '25 06:09

Ronak Shah